无法插入的byte []到MySQL用java(Can't insert byte[] in

2019-07-03 14:14发布

以下是我所使用的代码:

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();

而下面是我得到了一个错误:

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

我的MySQL 5.0.41和mysql-connector-java-5.1.7-bin.jar作为JDBC库。 是否有人可以帮助我在这里? 提前致谢!

Answer 1:

问题是,你的列被称为“钥匙”是SQL中保留字。 用反引号括起来,事情应该工作。 更重要的是,考虑重命名该列的东西,是不是一个SQL保留字。 我用下面的代码证明了这一点:

MySQL表:

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

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


Answer 2:

尝试使用“的setBinaryStream()”而不是“setBytes()”,并通过它您的字节数组构造一个ByteArrayInputStream。 这当然,假定分配给列的数据类型可以存储字节...确保它是一个BLOB,binary或varbinary。

此外,使用反引号包围你的对象。 “钥匙”是一个SQL关键字,并且除此以外,它仅仅是一个良好的习惯:

String query = "INSERT INTO `keytable` (`name`, `key`) VALUES (?,?)";


Answer 3:

您应该添加一个二进制流。 你可以访问InputStream的? 像这样..

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());


文章来源: Can't insert byte[] into MySQL using java
标签: java mysql jdbc