如何使用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......
廣告