如何使用 Java 程序将图像插入 MySQL 数据库?

java 8mysqlmysqli database

在 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://localhost/sampleDB,其中 sampleDB 是数据库名称)、用户名和密码作为参数传递给 getConnection() 方法,连接到 MySQL 数据库。

String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");

步骤 2:创建 Prepared 语句

使用 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");
//插入 Blob 类型
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://localhost/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......

相关文章