无法使用java将byte []插入MySQL [英] Can't insert byte[] into MySQL using java
本文介绍了无法使用java将byte []插入MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我使用的代码:
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库。
有人可以帮帮我吗?
提前致谢!
I have MySQL 5.0.41 and mysql-connector-java-5.1.7-bin.jar
as JDBC library.
Is anyone can help me out here?
Thanks in advance!
推荐答案
问题是你的名为key的列是SQL中的保留字。用反引号围绕它,事情应该有效。更好的是,考虑将列重命名为不是SQL保留字的内容。我已经使用下面的代码证明了这一点:
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表:
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 :)");
}
}
这篇关于无法使用java将byte []插入MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文