Java JDBC How to - Insert byte[] into MySQL








Question

We would like to know how to insert byte[] into MySQL.

Answer

Java code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/* ww  w.  j a va2  s  . co m*/
public class Main {
  public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection conn = null;
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
        "root", "password");
    byte[] bkey = "This is some binary stuff".getBytes();
    String query = "INSERT INTO keytable (name, `key`) VALUES (?,?)";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setString(1, "test");
    pstmt.setBytes(2, bkey);
    pstmt.execute();
    conn.close();
  }
}

SQL

create table keytable (name varchar(255) not null, `key` blob not null);