gpt4 book ai didi

java - 准备好的语句执行查询错误(com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException)

转载 作者:行者123 更新时间:2023-11-29 18:35:53 24 4
gpt4 key购买 nike

我编写了一个简单的方法来从数据库中获取字符串:

    public String getUserString(int id, String table, String column) {
String output = null;
try {
String sql = "SELECT ? FROM ? WHERE id=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, column);
preparedStatement.setString(2, table);
preparedStatement.setInt(3, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
return output;
}

但是当我尝试像这样使用它时: coreMySQL.getUserString(1, "economy", "balance");

我收到此错误: https://pastebin.com/BMAmN4Xh

最佳答案

您无法使用 PreparedStatementsetXxx 方法设置表名和列名。它只能用于设置值。

但是,您可以执行简单的 String 替换来替换表名称和列名称,例如:

String query = SELECT <column> FROM <table> WHERE id=?;
String sql = query.replaceAll("<column>", column).replaceAll("<table>", table);
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}

关于java - 准备好的语句执行查询错误(com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45304618/

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