gpt4 book ai didi

java - 设置字符串时出现 MySQLSyntaxErrorException

转载 作者:行者123 更新时间:2023-11-30 00:45:29 26 4
gpt4 key购买 nike

我有一个奇怪的问题。当我在以下代码段中执行查询时,它会抛出 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();
}
}

效果很好。你能帮我找出为什么第一个例子中的语法是错误的吗?

最佳答案

在第一种情况下,您还提供了表名称作为参数。准备好的语句将列名作为参数。使用prepareStatement时需要在语句中提供表名

关于java - 设置字符串时出现 MySQLSyntaxErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21406483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com