Getting and Inserting Binary Data into an Database Table - Java JDBC

Java examples for JDBC:Binary Data

Description

Getting and Inserting Binary Data into an Database Table

Demo Code

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Connection connection = null;
    // Prepare a statement to insert binary data
    String sql = "INSERT INTO mysql_all_table (col_binarystream) VALUES(?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);

    // Create some binary data
    byte[] buffer = "some data".getBytes();

    // Set value for the prepared statement
    pstmt.setBytes(1, buffer);/*  w w  w  .  j a va 2  s .  co  m*/

    // Insert the data
    pstmt.executeUpdate();
    pstmt.close();

    // Select records from the table
    Statement stmt = connection.createStatement();
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM mysql_all_table");
    while (resultSet.next()) {
      // Get data from the binary column
      byte[] bytes = resultSet.getBytes("col_binarystream");
    }
  }
}

Related Tutorials