How to read a blob field in Java?

One way to read Blob fields in Java is by using the methods provided by the java.sql.Blob interface. Here is a simple example:

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.sql.*;

public class BlobReader {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/mydatabase";

        String username = "root";

        String password = "password";

        try {

            Connection conn = DriverManager.getConnection(url, username, password);

            String sql = "SELECT blob_column FROM my_table WHERE id = ?";

            PreparedStatement statement = conn.prepareStatement(sql);

            statement.setInt(1, 1);

            ResultSet result = statement.executeQuery();

            if (result.next()) {

                Blob blob = result.getBlob("blob_column");

                InputStream inputStream = blob.getBinaryStream();

                FileOutputStream outputStream = new FileOutputStream("output_file.txt");

                int bytesRead;

                byte[] buffer = new byte[4096];

                while ((bytesRead = inputStream.read(buffer)) != -1) {

                    outputStream.write(buffer, 0, bytesRead);

                }

                inputStream.close();

                outputStream.close();

            }

            conn.close();

        } catch (SQLException | IOException e) {

            e.printStackTrace();

        }

    }

}

In the example above, connecting to a database via JDBC and executing a SELECT statement to retrieve a Blob field. Then, using the getBinaryStream() method of the Blob object to get the input stream, and then writing it to a file output stream. Note: In actual use, need to replace `url`, `username`, `password`, `sql`, and the output file path. Additionally, proper handling of exceptions and closing connections is also required.

广告
Closing in 10 seconds
bannerAds