PreparedStatement 接口的setBinaryStream()方法接受表示参数索引和输入流对象的整数,并将参数设置为给定的输入流对象。每当需要发送非常大的二进制值时,都可以使用此方法。
SQL数据库提供了一个名为Blob(二进制大对象)的数据类型,您可以在其中存储诸如图像之类的大型二进制数据。
如果需要使用JDBC程序将图像存储在数据库中,请创建具有Blob数据类型的表,如下所示:
CREATE TABLE Tutorial(Name VARCHAR(255), Type INT NOT NULL, Logo BLOB);
现在,使用JDBC,连接到数据库并准备PreparedStatement,以将值插入到上面创建的表中:
String query = "INSERT INTO Tutorial(Name, Type, Logo) VALUES (?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query);
使用PreparedStatement接口的setter方法为占位符设置值,并使用方法为Blob数据类型设置值setBinaryStream()
。
FileInputStream fin = new FileInputStream("javafx_logo.jpg");pstmt.setBinaryStream(3, fin);
以下是演示如何使用JDBC程序将图像插入MySQL数据库的示例。在这里,我们正在创建一个表,其中的blob数据类型向表中插入了值(Blob类型的BinaryStream对象),并检索了表的内容。
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class InsertingImageToDatabase { public static void main(String args[]) throws Exception { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获得连接 String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建语句 Statement stmt = con.createStatement(); //执行语句 String createTable = "CREATE TABLE Tutorial( " + "Name VARCHAR(255), " + "Type VARCHAR(50), " + "Logo BLOB)"; stmt.execute(createTable); //插入值 String query = "INSERT INTO Tutorial(Name, Type, Logo) VALUES (?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "JavaFX"); pstmt.setString(2, "Java_library"); FileInputStream fin = new FileInputStream("E:\\images\\javafx_logo.jpg"); pstmt.setBinaryStream(3, fin); pstmt.execute(); pstmt.setString(1, "CoffeeScript"); pstmt.setString(2, "scripting Language"); fin = new FileInputStream("E:\\images\\coffeescript_logo.jpg"); pstmt.setBinaryStream(3, fin); pstmt.execute(); pstmt.setString(1, "Cassandra"); pstmt.setString(2, "NoSQL database"); fin = new FileInputStream("E:\\images\\cassandra_logo.jpg"); pstmt.setBinaryStream(3, fin); pstmt.execute(); System.out.println("Data inserted"); ResultSet rs = stmt.executeQuery("Select *from Tutorial"); while(rs.next()) { System.out.print("Name: "+rs.getString("Name")+", "); System.out.print("Tutorial Type: "+rs.getString("Type")+", "); System.out.print("Logo: "+rs.getBlob("Logo")); System.out.println(); } } }
Connection established...... Data inserted Name: JavaFX, Tutorial Type: Java_library, Logo: com.mysql.jdbc.Blob@7dc5e7b4 Name: CoffeeScript, Tutorial Type: scripting Language, Logo: com.mysql.jdbc.Blob@1ee0005 Name: Cassandra, Tutorial Type: NoSQL database, Logo: com.mysql.jdbc.Blob@75a1cd57
注意:您只能使用JDBC程序存储和检索.gif或.jpeg或.png类型的图像。