Following is the code I have used:
byte[] bkey = key.getEncoded();
String query = \"INSERT INTO keytable (name, key) VALUES (?,?)\";
PreparedStatement pstmt
The problem is that your column called "key" is a reserve word in SQL. Surround it with backticks and things should work. Better yet, consider renaming the column to something that is not a SQL reserve word. I've proven this out using the code below:
MySQL table:
create table keytable (name varchar(255) not null, `key` blob not null);
Java code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MySQLBlobInsert {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
Connection conn = null;
try {
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();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
System.out.println("done :)");
}
}
Try using "setBinaryStream()" instead of "setBytes()", and pass it a ByteArrayInputStream constructed on your byte array. This, of course, assumes that the data type assigned to the column can store bytes... Make sure it is a BLOB, BINARY, or VARBINARY.
Also, use backticks to enclose your objects. "key" is a SQL keyword, and other than that it is just a good habit:
String query = "INSERT INTO `keytable` (`name`, `key`) VALUES (?,?)";
You should add a binary stream. Do you have access to the inputstream ?? like this..
FileInputStream input = new FileInputStream("myfile.gif");
String query = "INSERT INTO `keytable` (`name`, `key`) VALUES (?,?)";
PreparedStatement pstmt = (PreparedStatement) connection.prepareStatement(query);
pstmt.setString(1, "test");
pstmt.setBinaryStream(2, input, input.available());