編寫一個 JDBC 示例,用於將 Blob 資料型別的值插入到表中?


假設我們已經在資料庫中有一個名為 MyTable 的表,其描述如下。

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

如果您需要使用 JDBC 程式將值插入到 blob 資料型別中,則需要使用設定二進位制流資料的方法。PreparedStatement 介面提供以下方法將影像插入到表中。

**void setBinaryStream(int parameterIndex, InputStream x)** 方法將給定輸入流中的資料(直到檔案末尾)作為值設定為給定索引處的引數。

此方法的其他變體是

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

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

**void setBlob(int parameterIndex, Blob x)** 方法將給定的 blob 物件作為值設定為給定索引處的引數。

此方法的其他變體是

  • void setBlob(int parameterIndex, InputStream inputStream)

  • void setBlob(int parameterIndex, InputStream 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:///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 值,則可以看到插入的影像,如下所示

更新於: 2019年7月30日

2K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告