gpt4 book ai didi

java - PrepareStatement 错误

转载 作者:搜寻专家 更新时间:2023-10-30 19:59:37 25 4
gpt4 key购买 nike

我在这个函数中遇到错误,但我不知道为什么。你能帮帮我吗?

错误在我调用 executeQuery()

的行中
public static int numeroElementi(String table) throws SQLException {

// viene reistanziata perché questa è una funziona statica!
String DB_URL = "jdbc:mysql://localhost:3306/kmzero";
Connection connection = DriverManager.getConnection(DB_URL, "root", "root");

String query = "SELECT COUNT(*) AS count FROM ? ";
PreparedStatement pStatement = connection.prepareStatement(query);
pStatement.setString(1, table);

try {

ResultSet resultSet = pStatement.executeQuery();

try {
if (resultSet.next())
return resultSet.getInt("count");

else
return 0;

} finally {
resultSet.close();
}
} finally {
pStatement.close();
}
}

最佳答案

我认为您不能将 tablename(还有 columnNames)作为参数传递,此时 tableName 应该在您的字符串。

String query = "SELECT COUNT(*) AS count FROM " + table;

如果你的表需要转义,

String query = "SELECT COUNT(*) AS count FROM `" + table + "`";

关于java - PrepareStatement 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13432082/

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