เมธอด setBinaryStream() ของ PreparedStatement รับ index และ InputStream ใช้ส่งข้อมูล binary ขนาดใหญ่ ฐานข้อมูล SQL มีชนิด Blob (Binary Large Object) เก็บข้อมูล binary ขนาดใหญ่ เช่น รูปภาพ
เก็บรูปภาพด้วย JDBC
สร้างตารางมีคอลัมน์ BLOB:
CREATE TABLE Tutorial(Name VARCHAR(255), Type INT NOT NULL, Logo BLOB);
เตรียม PreparedStatement:
String query = "INSERT INTO Tutorial(Name, Type, Logo) VALUES (?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query);
ตั้งค่า placeholder สำหรับ BLOB ใช้ setBinaryStream():
FileInputStream fin = new FileInputStream("javafx_logo.jpg");
pstmt.setBinaryStream(3, fin);
ตัวอย่าง
โปรแกรมสร้างตาราง insert 3 รูปภาพ แล้วดึงข้อมูล:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertingImageToDatabase {
public static void main(String args[]) throws Exception {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
Statement stmt = con.createStatement();
String createTable = "CREATE TABLE Tutorial("
+ "Name VARCHAR(255), "
+ "Type VARCHAR(50), "
+ "Logo BLOB)";
stmt.execute(createTable);
String query = "INSERT INTO Tutorial(Name, Type, Logo) VALUES (?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "JavaFX");
pstmt.setString(2, "Java_library");
FileInputStream fin = new FileInputStream("E:\\images\\javafx_logo.jpg");
pstmt.setBinaryStream(3, fin);
pstmt.execute();
pstmt.setString(1, "CoffeeScript");
pstmt.setString(2, "scripting Language");
fin = new FileInputStream("E:\\images\\coffeescript_logo.jpg");
pstmt.setBinaryStream(3, fin);
pstmt.execute();
pstmt.setString(1, "Cassandra");
pstmt.setString(2, "NoSQL database");
fin = new FileInputStream("E:\\images\\cassandra_logo.jpg");
pstmt.setBinaryStream(3, fin);
pstmt.execute();
System.out.println("Data inserted");
ResultSet rs = stmt.executeQuery("Select * from Tutorial");
while(rs.next()) {
System.out.print("Name: " + rs.getString("Name") + ", ");
System.out.print("Tutorial Type: " + rs.getString("Type") + ", ");
System.out.print("Logo: " + rs.getBlob("Logo"));
System.out.println();
}
}
}
ผลลัพธ์
Connection established...... Data inserted Name: JavaFX, Tutorial Type: Java_library, Logo: com.mysql.jdbc.Blob@7dc5e7b4 Name: CoffeeScript, Tutorial Type: scripting Language, Logo: com.mysql.jdbc.Blob@1ee0005 Name: Cassandra, Tutorial Type: NoSQL database, Logo: com.mysql.jdbc.Blob@75a1cd57
หมายเหตุ: JDBC รองรับเก็บ/ดึงรูปภาพได้เฉพาะ .gif, .jpeg, .png เท่านั้น