我编写了一个简单的方法来从数据库中获取字符串:
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
最佳答案
您无法使用 PreparedStatement
的 setXxx
方法设置表名和列名。它只能用于设置值。
但是,您可以执行简单的 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/