Tags:

Cách đọc dữ liệu dạng File từ MySQL trong JDBC

Nếu bạn đã sử dụng JDBC để lưu các dữ liệu dạng file xuống database thì trong bài viết này chúng ta sẽ cùng nhau tìm hiểu cách để đọc ngược chúng từ database lên Java thông qua JDBC.

Chúng ta đều biết rằng kiểu dữ liệu BLOB trong MySQL được dùng để lưu trữ các dữ liệu dạng file. Khi thực thi một câu truy vấn trong JDBC, kết quả trả về sẽ nằm trong ResultSet, với JDBC thì chúng ta có thể sử dụng getBlob() để lấy dữ liệu dạng Blob từ ResultSet về.

ResultSet result = statement.executeQuery();
 
if (result.next()) {
    Blob blob = result.getBlob("photo");
    InputStream inputStream = blob.getBinaryStream();
    // read the input stream...
 
}

Ở trên là cách để chúng ta đọc dữ liệu dạng file từ MySQL và chuyển từ blob sang InputStream. Các bạn có thể xem ví dụ đầy đủ ngay sau đây

import java.io.*;
import java.sql.*;

public class Main {

    private static final int BUFFER_SIZE = 4096;

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/contactdb";
        String user = "root";
        String password = "secret";

        String filePath = "D:/Photos/Tom.jpg";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {

            String sql = "SELECT photo FROM person WHERE first_name=? AND last_name=?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, "Tom");
            statement.setString(2, "Eagar");

            ResultSet result = statement.executeQuery();
            if (result.next()) {
                Blob blob = result.getBlob("photo");
                InputStream inputStream = blob.getBinaryStream();
                OutputStream outputStream = new FileOutputStream(filePath);

                int bytesRead = -1;
                byte[] buffer = new byte[BUFFER_SIZE];
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                System.out.println("File saved");
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Nguồn

https://www.codejava.net/java-se/jdbc/read-file-data-from-database-using-jdbc

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x