📅  最后修改于: 2020-10-13 01:28:19             🧑  作者: Mango
您可以借助PreparedStatement接口将图像存储在Java数据库中。
PreparedStatement的setBinaryStream()方法用于将Binary信息设置为parameterIndex。
setBinaryStream()方法的语法如下:
1) public void setBinaryStream(int paramIndex,InputStream stream)
throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream,long length)
throws SQLException
为了将图像存储到数据库中,表中使用了BLOB(二进制大对象)数据类型。例如:
CREATE TABLE "IMGTABLE"
("NAME" VARCHAR2(4000),
"PHOTO" BLOB
)
/
让我们编写jdbc代码以将图像存储在数据库中。在这里,我们使用d:\\ d.jpg作为图像的位置。您可以根据图像位置进行更改。
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();}
}
}
如果您看到该表,则记录存储在数据库中,但不会显示图像。为此,您需要从我们将在下一页介绍的数据库中检索图像。