Discussion (1)2
Log in or sign up to continue

Hi Zhang,

you'll find a JDBC example below : 

import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class RetrieveBlob {

  public static void main(String[] args) throws Exception {
    // Replace with your connection details
    String url = "jdbc:mysql://localhost:3306/your_database";
    String username = "your_username";
    String password = "your_password";

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

    String sql = "SELECT image FROM your_table WHERE id = ?";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setInt(1, 1); // Replace with the ID you want to query

    ResultSet rs = stmt.executeQuery();

    if (rs.next()) {
      Blob blob = rs.getBlob("image"); // Replace "image" with your column name

      // Option 1: Get Bytes
      byte[] imageBytes = blob.getBytes(1, (int) blob.length()); // Get all bytes
      // Process the imageBytes byte array

      // Option 2: Stream Processing
      // InputStream in = blob.getBinaryStream();
      // ... process the stream
    }

    rs.close();
    stmt.close();
    conn.close();
  }
}