我有一个奇怪的问题。当我在下面的代码段中执行查询时,它会抛出一条带有消息的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
''fantasy' SET Quantity = 3 WHERE BookName = 'The Silmarilion'' at line 1
代码:
private void updateDBTable(String category, Vector dataVector) {
try {
for(int i = 0; i < dataVector.size(); i++) {
String bookName = String.valueOf(((Vector) dataVector.elementAt(i))
.elementAt(0));
int quantity = (int) ((Vector) dataVector.elementAt(i))
.elementAt(4);
statement = databaseConnection
.prepareStatement("UPDATE ? SET Quantity = ? WHERE BookName = ?");
statement.setString(1, category);
statement.setInt(2, quantity);
statement.setString(3, bookName);
statement.executeUpdate();
}
}
但如果我这样写:
private void updateDBTable(String category, Vector dataVector) {
try {
for(int i = 0; i < dataVector.size(); i++) {
String bookName = String.valueOf(((Vector) dataVector.elementAt(i))
.elementAt(0));
bookName = "'" + bookName + "'";
int quantity = (int) ((Vector) dataVector.elementAt(i))
.elementAt(4);
statement = databaseConnection
.prepareStatement("UPDATE " +
category +
" SET Quantity = ? WHERE BookName = " +
bookName);
statement.setInt(1, quantity);
statement.executeUpdate();
}
}
工作正常。你能帮我弄清楚为什么第一个例子中的语法是错误的吗?
答案 0 :(得分:0)
在第一种情况下,您还提供了表名作为参数。准备好的语句将列名称作为参数。您需要在使用prepareStatement
时在语句中提供表名