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

Ví dụ JDBC chèn giá trị cho kiểu Blob vào bảng?


Giả sử đã có bảng MyTable trong database với mô tả:

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

Để chèn giá trị vào kiểu blob dùng JDBC, cần dùng phương thức thiết lập binary stream. PreparedStatement cung cấp các phương thức sau để chèn ảnh:

Phương thức void setBinaryStream(int parameterIndex, InputStream x) thiết lập dữ liệu trong input stream (đến cuối file) làm giá trị cho tham số tại chỉ số đã cho.

Các biến thể khác:

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

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

Phương thức void setBlob(int parameterIndex, Blob x) thiết lập đối tượng blob cho tham số tại chỉ số đã cho.

Các biến thể khác:

  • void setBlob(int parameterIndex, InputStream inputStream)

  • void setBlob(int parameterIndex, InputStream inputStream, long length)

Bạn có thể dùng một trong các phương thức này để thiết lập giá trị cho kiểu Blob.

Ví dụ

Ví dụ thiết lập giá trị cho kiểu Blob dùng setBinaryStream():

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{ 
        // Đă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......"); 
        // Chèn giá trị 
        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("Bản ghi đã chèn ....."); 
    } 
}

Kết quả

Kết nối thành công...... 
Bản ghi đã chèn ......

Nếu xem giá trị blob trong bản ghi bằng MySQL Workbench, thấy ảnh đã chèn:

Ví dụ JDBC chèn giá trị cho kiểu Blob vào bảng?