如何使用 Java 程式將影像插入 Oracle 資料庫?


要在 Oracle 資料庫中儲存影像,通常使用 blob 型別。因此,請確保您建立了一個包含 blob 資料型別的表,如下所示:

Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(255)
IMAGE BLOB

要將影像插入 **Oracle** 資料庫,請按照以下步驟操作:

步驟 1:連線到資料庫

您可以使用 **DriverManager** 類的 **getConnection()** 方法連線到資料庫。

透過將 Oracle URL(對於 Express 版為 **jdbc:oracle:thin:@localhost:1521/xe**),使用者名稱和密碼作為引數傳遞給 getConnection() 方法,連線到 Oracle 資料庫。

String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "user_name", "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 InsertImageToOracleDB {
   public static void main(String args[]) throws Exception{
      //Registering the Driver
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ());
      //Getting the connection
      String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
      Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
      System.out.println("Connected to Oracle database.....");
      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");
   }
}

輸出

Connected to Oracle database.....
Record inserted.....

更新時間: 2019-07-30

5K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告