Can't insert byte[] into MySQL using java

前端 未结 3 730
夕颜
夕颜 2021-01-13 08:59

Following is the code I have used:

byte[] bkey = key.getEncoded();
String query = \"INSERT INTO keytable (name, key) VALUES (?,?)\";
PreparedStatement pstmt          


        
3条回答
  •  伪装坚强ぢ
    2021-01-13 09:39

    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 :)");
        }
    }
    

提交回复
热议问题