无法使用java将byte []插入MySQL

5 java mysql jdbc

以下是我使用的代码:

byte[] bkey = key.getEncoded();
String query = "INSERT INTO keytable (name, key) VALUES (?,?)";
PreparedStatement pstmt = (PreparedStatement) connection.prepareStatement(query);
pstmt.setString(1, "test");
pstmt.setBytes(2, bkey);
pstmt.execute();
Run Code Online (Sandbox Code Playgroud)

以下是我得到的错误:

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key) VALUES ('test',_binary'????s??u\'?}p?u')' at line 1
Run Code Online (Sandbox Code Playgroud)

我有MySQL 5.0.41和mysql-connector-java-5.1.7-bin.jarJDBC库.有人可以帮帮我吗?提前致谢!

Asa*_*aph 10

问题是你的名为"key"的列是SQL中的保留字.用反引号围绕它,事情应该有效.更好的是,考虑将列重命名为不是SQL保留字的内容.我已经使用下面的代码证明了这一点:

MySQL表:

create table keytable (name varchar(255) not null, `key` blob not null);
Run Code Online (Sandbox Code Playgroud)

Java代码:

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 :)");
    }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*han 0

尝试使用“setBinaryStream()”而不是“setBytes()”,并向其传递一个在字节数组上构造的 ByteArrayInputStream。当然,这是假设分配给列的数据类型可以存储字节...确保它是 BLOB、BINARY 或 VARBINARY。

另外,使用反引号将对象括起来。“key”是一个 SQL 关键字,除此之外它只是一个好习惯:

String query = "INSERT INTO `keytable` (`name`, `key`) VALUES (?,?)";
Run Code Online (Sandbox Code Playgroud)