如何在sql数据库中保存图像并在datagridview列中检索

如何在sql数据库中保存图像并在datagridview列中检索

本文介绍了如何在sql数据库中保存图像并在datagridview列中检索它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个文本框,一个是条形码图像我想在sql server中添加它并检索它我该怎么办,你可以帮助我吗?

i have 2 textboxes and one is barcode image i want to add it in sql server and retrive it how can i do, can u help me ?

推荐答案

public void saveImage(File file){
        try {
            String img_id=JOptionPane.showInputDialog("Enter Image ID");
            FileInputStream fis=null;
            String query="insert into image(image_id,image) values (?,?)";
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con=DriverManager.getConnection("jdbc:odbc:image");
            PreparedStatement pstm=con.prepareStatement(query);
            fis=new FileInputStream(file);
            pstm.setString(1, img_id);
            pstm.setBinaryStream(2, (InputStream)fis, (int)file.length());
            pstm.executeUpdate();
            JOptionPane.showMessageDialog(null, "Image Successfully Uploaded to Database");
            pstm.close();
            con.close();

        } catch (Exception ex) {
            System.out.println("Exception Occured: "+ex);
        }
    }





通过再次从二进制制作图像并将其保存在某个物理位置来检索它:



And Retrieve it by again making Image from binary and Save it on some physical Location:

public void getSavedImages(){
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:odbc:image");
            PreparedStatement pstm1 = con.prepareStatement("select * from image");
            ResultSet rs1 = pstm1.executeQuery();
            while(rs1.next()) {
                InputStream fis1;
                FileOutputStream fos;
                String image_id;
                try {
                    fis1 = rs1.getBinaryStream("image");
                    image_id=rs1.getString("image_id");
                    fos = new FileOutputStream(new File(Path to "C:\\" + (image_id) + "Your Extension(.jpg/.gif)"));
                    int c;
                    while ((c = fis1.read()) != -1) {
                        fos.write(c);
                    }
                    fis1.close();
                    fos.close();

                } catch (Exception ex) {
                    System.out.println(ex);
                }
            }
            pstm1.close();
            con.close();
        } catch (Exception ex) {
            System.out.println("Exception Occured:"+ex);
        }
    }





谢谢



Thanks


//Read the byte array from database and then use the following method to //convert the byte array back into image
 public static Image DB2Image(byte[] byteArrayIn)
  {
   MemoryStream ms = new MemoryStream(byteArrayIn);
   Image returnImage = Image.FromStream(ms);
   return returnImage;
  }



这篇关于如何在sql数据库中保存图像并在datagridview列中检索它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:15