易百教程

356、如何从数据库中存储和检索图像?

通过使用 PreparedStatement 接口,可以存储和检索图像。创建一个包含两列即 NAMEPHOTO 的表。

CREATE TABLE  "IMGTABLE" (    
    "NAME" VARCHAR2(4000),   
    "PHOTO" BLOB  
)

参考以下示例以将图像存储在数据库中:


import java.sql.*;
import java.io.*;

public class InsertImage {

    public static void main(String[] args) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");

            PreparedStatement ps = con.prepareStatement("insert into imgtable values(?,?)");
            ps.setString(1, "sonoo");

            FileInputStream fin = new FileInputStream("d:\\g.jpg");
            ps.setBinaryStream(2, fin, fin.available());
            int i = ps.executeUpdate();
            System.out.println(i + " records affected");

            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

参考以下示例以从表中检索图像:


import java.sql.*;
import java.io.*;

public class RetrieveImage {

    public static void main(String[] args) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");

            PreparedStatement ps = con.prepareStatement("select * from imgtable");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {//now on 1st row  

                Blob b = rs.getBlob(2);//2 means 2nd column data  
                byte barr[] = b.getBytes(1, (int) b.length());//1 means first image  

                FileOutputStream fout = new FileOutputStream("d:\\sonoo.jpg");
                fout.write(barr);

                fout.close();
            }//end of if  
            System.out.println("ok");

            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}