以下是我使用的代码:
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库。
有人可以帮帮我吗?
提前谢谢!
答案 0 :(得分:10)
问题是你的名为“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 :)");
}
}
答案 1 :(得分:0)
尝试使用“setBinaryStream()”而不是“setBytes()”,并传递一个在字节数组上构造的ByteArrayInputStream。当然,这假定分配给列的数据类型可以存储字节...确保它是BLOB,BINARY或VARBINARY。
此外,使用反引号来封闭您的对象。 “key”是一个SQL关键字,除此之外它只是一个好习惯:
String query = "INSERT INTO `keytable` (`name`, `key`) VALUES (?,?)";
答案 2 :(得分:-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());