如何使用Java程序将图像插入MySQL数据库?
要在 MySQL 数据库中存储图像,通常使用 blob 类型。因此,请确保您已创建包含 blob 数据类型 的表,其描述如下:
+-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | image | blob | YES | | NULL | | +-------+--------------+------+-----+---------+-------+
要将图像插入MySQL 数据库,请按照以下步骤操作:
步骤 1:连接到数据库
您可以使用 DriverManager 类的 连接到数据库 getConnection() 方法。
通过将 MySQL URL(即 **jdbc:mysql:///sampleDB**(其中 sampleDB 是数据库名称))、用户名和密码作为参数传递给 getConnection() 方法来连接到 MySQL 数据库。
String mysqlUrl = "jdbc:mysql:///sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
步骤 2:创建预处理语句
使用 **Connection** 接口的 **prepareStatement()** 方法创建一个 PreparedStatement 对象。将插入查询(带占位符)作为参数传递给此方法。
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");步骤 3:设置占位符的值
使用 **PreparedStatement** 接口的 setter 方法设置占位符的值。根据列的数据类型选择方法。例如,如果列是 VARCHAR 类型,则使用 **setString()** 方法;如果列是 INT 类型,则可以使用 **setInt()** 方法。
如果列是 Blob 类型,则可以使用 **setBinaryStream()** 或 setBlob() 方法为其设置值。将表示参数索引的整数变量和 InputStream 类的对象作为参数传递给这些方法。
pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\images\cat.jpg");
pstmt.setBlob(2, in);步骤 4:执行语句
使用 **PreparedStatement** 接口的 **execute()** 方法执行上面创建的 PreparedStatement 对象。
示例
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertImageToMySqlDB {
public static void main(String args[]) throws Exception{
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql:///sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)");
pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\images\cat.jpg");
pstmt.setBlob(2, in);
//Executing the statement
pstmt.execute();
System.out.println("Record inserted......");
}
}输出
Connection established...... Record inserted......
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP