Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

JDBC Blob data type là gì? Cách lưu và đọc dữ liệu từ nó?


BLOB (Binary Large Object) lưu dữ liệu binary biến đổi, tối đa 65535 ký tự. Dùng lưu dữ liệu binary lớn: ảnh, file. Trường TEXT cũng lưu dữ liệu lớn. Khác biệt: so sánh/sắp xếp trên BLOB phân biệt chữ hoa/thường, TEXT thì không. Không chỉ định độ dài cho BLOB/TEXT.

Lưu blob vào database

Các bước lưu Blob datatype dùng JDBC:

Bước 1: Kết nối database

Dùng getConnection() của DriverManager. Kết nối MySQL URL jdbc:mysql://localhost/sampleDB, username, password:

String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; 
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");

Bước 2: Tạo PreparedStatement

Tạo PreparedStatement bằng prepareStatement() của Connection. Truyền câu insert có placeholder:

PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");

Bước 3: Thiết lập giá trị cho placeholder

Dùng setter methods của PreparedStatement. Với Blob dùng setBinaryStream() hoặc setBlob(). Truyền chỉ số tham số và InputStream object:

pstmt.setString(1, "sample image"); 
// Chèn Blob 
InputStream in = new FileInputStream("E:\\images\\cat.jpg"); 
pstmt.setBlob(2, in);

Bước 4: Thực thi statement

Thực thi PreparedStatement bằng execute() của PreparedStatement.

Truy xuất blob từ database

Phương thức getBlob() của ResultSet nhận chỉ số cột hoặc tên cột, trả về Blob object.

while(rs.next()) { 
    rs.getString("Name"); 
    rs.getString("Type"); 
    Blob blob = rs.getBlob("Logo"); 
}

Phương thức getBytes() của interface Blob lấy nội dung Blob object hiện tại trả về byte array.

Dùng getBlob() lấy nội dung blob vào byte array, tạo ảnh bằng write() của FileOutputStream:

byte byteArray[] = blob.getBytes(1, (int)blob.length()); 
FileOutputStream outPutStream = new FileOutputStream("path"); 
outPutStream.write(byteArray);

Ví dụ

Ví dụ tạo bảng MySQL có blob, chèn ảnh, truy xuất lưu vào file system:

import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.sql.Blob; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.Statement; 

public class BlobExample { 
    public static void main(String args[]) throws Exception { 
        // Đăng ký Driver 
        DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 
        // Lấy kết nối 
        String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; 
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); 
        System.out.println("Kết nối thành công......"); 
        // Tạo bảng 
        Statement stmt = con.createStatement(); 
        stmt.execute("CREATE TABLE SampleTable( Name VARCHAR(255), Image BLOB)"); 
        System.out.println("Bảng đã tạo"); 
        // Chèn giá trị 
        String query = "INSERT INTO SampleTable(Name,image) VALUES (?, ?)"; 
        PreparedStatement pstmt = con.prepareStatement(query); 
        pstmt.setString(1, "sample image"); 
        FileInputStream fin = new FileInputStream("E:\\images\\cat.jpg"); 
        pstmt.setBlob(2, fin); 
        pstmt.execute(); 
        // Truy xuất dữ liệu 
        ResultSet rs = stmt.executeQuery("select * from SampleTable"); 
        int i = 1; 
        System.out.println("Nội dung bảng:"); 
        while(rs.next()) { 
            System.out.println(rs.getString("Name")); 
            Blob blob = rs.getBlob("Image"); 
            byte byteArray[] = blob.getBytes(1, (int)blob.length()); 
            FileOutputStream outPutStream = new FileOutputStream("E:\\images\\blob_output" + i + ".jpg"); 
            outPutStream.write(byteArray); 
            System.out.println("E:\\images\\blob_output" + i + ".jpg"); 
            System.out.println(); 
            i++; 
        } 
    } 
}

Kết quả

Kết nối thành công...... 
Bảng đã tạo 
Nội dung bảng: 
sample image 
E:\images\blob_output1.jpg