【问题标题】:Can't insert byte[] into MySQL using java无法使用 java 将字节 [] 插入 MySQL
【发布时间】:2009-08-24 20:41:57
【问题描述】:

以下是我使用的代码:

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 库。 有人可以帮我吗? 提前致谢!

【问题讨论】:

  • 您能否在您的表上执行“描述 ”并向我们展示输出,以便我们知道您正在处理哪些列类型?

标签: java mysql jdbc


【解决方案1】:

问题是您的“key”列是 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 :)");
    }
}

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 更新了另一个建议。
    【解决方案3】:

    您应该添加一个二进制流。您可以访问输入流吗?像这样..

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

    【讨论】:

    • input.available() 返回长度。
    猜你喜欢
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多