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

Cách chèn ảnh vào database MySQL bằng chương trình Java?


Để lưu ảnh trong MySQL, thường dùng kiểu blob. Đảm bảo có bảng với kiểu blob như sau:

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

Các bước chèn ảnh vào MySQL database:

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

Dùng phương thức getConnection() của DriverManager. Kết nối MySQL bằng 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 interface Connection. Truyền câu insert (có placeholder) làm tham số:

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. Chọn phương thức theo kiểu cột: VARCHAR dùng setString(), INT dùng setInt(). Với Blob dùng setBinaryStream() hoặc setBlob(). Truyền chỉ số tham số và đối tượng InputStream:

pstmt.setString(1, "sample image"); 
// Chèn kiểu 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 phương thức execute() của interface PreparedStatement.

Ví dụ

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{ 
        // Đă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......"); 
        PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)"); 
        pstmt.setString(1, "sample image"); 
        // Chèn Blob 
        InputStream in = new FileInputStream("E:\\images\\cat.jpg"); 
        pstmt.setBlob(2, in); 
        // Thực thi 
        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......