技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

编写一个 JDBC 示例,用于将 Blob 数据类型的值插入表中?

jdbcjava 8mysqlmysqli database

假设数据库中已经有一个名为 MyTable 的表,其描述如下。

+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Name  | varchar(255) | YES  |     | NULL    |       |
| image | blob         | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+

如果您需要使用 JDBC 程序将值 int 插入到 blob 数据类型,则需要使用设置二进制流数据的方法。 PreparedStatement 接口提供以下方法将图像插入表中。

void setBinaryStream(int paramterIndex, InputStream x) 方法将给定输入流(直到文件末尾)中的数据设置为给定索引处的参数的值。

此方法的其他变体是

  • void setBinaryStream(int paramterIndex, InputStream x, int length)

  • void setBinaryStream(int paramterIndex, InputStream x, long length)

void setBlob(int paramterIndex, Blob x) 方法将给定的 blob 对象设置为给定索引处的参数的值。

此方法的其他变体是

  • void setBlob(int 参数索引,InputStream 输入流)

  • void setBlob(int 参数索引,InputStream 输入流,long length)

您可以使用上述任一方法将值设置为 Blob 数据类型。

示例

以下示例使用 setBinaryStream() 方法将值设置为 Blob 数据类型。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class IndertingValueForBlob {
   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......");

      //Inserting values
      String query = "INSERT INTO MyTable(Name,image) VALUES (?, ?)";
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setString(1, "sample_image");
      FileInputStream fin = new FileInputStream("E:\images\cat.jpg");
      pstmt.setBinaryStream(2, fin);
      pstmt.execute();
      System.out.println("Record inserted .....");
   }
}

输出

Connection established......
Record inserted ......

如果您尝试使用 MySQL 工作台查看记录中的 blob 值,您可以看到插入的图像,如下所示:


相关文章