MySQL 如何使用JDBC将图像插入数据库
PreparedStatement 接口的 setBinaryStream() 方法接受表示参数索引的整数和 InputStream 对象,并将参数设置为给定的 InputStream 对象。 每当您需要发送非常大的二进制值时,可以使用此方法。
SQL 数据库提供了名为 Blob (二进制大对象)的数据类型,其中可以存储大量二进制数据,如图像。
阅读更多:MySQL 教程
使用JDBC存储图像
如果需要使用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方法设置占位符的值,并使用setBinaryStream()方法设置Blob数据类型的值。
FileInputStream fin = new FileInputStream("javafx_logo.jpg");
pstmt.setBinaryStream(3, fin);
示例
以下是一个示例,演示如何使用JDBC程序将图像插入到MySQL数据库中。在这里,我们创建一个带有Blob数据类型的表,将值插入到表中(使用 BinaryStream 对象将值插入到Blob类型),并检索表的内容。
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("连接已建立......");
//创建语句
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("数据已插入");
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();
}
}
}
输出
连接已建立......
数据已插入
名称:JavaFX,教程类型:Java_library,Logo:com.mysql.jdbc.Blob@7dc5e7b4
名称:CoffeeScript,教程类型:脚本语言,Logo:com.mysql.jdbc.Blob@1ee0005
名称:Cassandra,教程类型:NoSQL数据库,Logo:com.mysql.jdbc.Blob@75a1cd57
注意: 使用JDBC程序只能存储和检索.gif、.jpeg或.png类型的图像。
极客教程