我一直试图找出为什么我准备好的陈述在我的字符串之前和之后放置'
。当我尝试将此代码用于我的Postgressql数据库服务器时,我收到语法错误。这是因为该程序按如下方式处理代码:
想象一下,我将此方法称为:
selectStringQuery("username", "users", "id", 1);
然后程序返回以下准备好的声明:
SELECT 'username' FROM 'users' WHERE 'id' = 1;
运行程序时出现以下错误:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$2"
Position: 16
它应该产生这个:
SELECT username FROM users WHERE id = 1;
有人可以告诉我,我在这里缺少什么吗?
* Executes a select query.
* @param selectFieldName
* @param tableName
* @param conditionFieldName
* @param conditionValue
* @return
*/public String selectStringQuery(String selectFieldName, String tableName, String conditionFieldName, int conditionValue){
try {
// *** Start execution of query ***
query = "SELECT ? FROM ? WHERE ? = ?;";
preparedStatement = prepareStatement(query);
preparedStatement.setString(1, selectFieldName);
preparedStatement.setString(2, tableName);
preparedStatement.setString(3, conditionFieldName);
preparedStatement.setInt(4, conditionValue);
System.out.println(preparedStatement);
resultSet = preparedStatement.executeQuery();
// *** End execution of query ***
// *** Start validity checks ***
if(!resultSet.next()){
System.out.println("Query did not return any results.");
return null;
}
// *** End validity checks ***
// *** Start process query results ***
String result = resultSet.getString(selectFieldName);
return result;
// *** End process query results ***
} catch (Exception ex) {
System.out.println(ex);
return null;
}
}
答案 0 :(得分:4)
尝试在查询字符串中合并表名和列名。
query = "SELECT "+selectFieldName+" FROM "+tableName+" WHERE "+conditionFieldName+" = ?;";
我认为你不能将表名和列名作为参数传递。参数被视为列值并且''
被添加到它们
答案 1 :(得分:0)
你可以试试这样的事情
query = "SELECT "+selectFieldName+" FROM "+tableName+" WHERE "+selectFieldName+" = ?;"
答案 2 :(得分:0)
参数不能用于参数化表,也不能参数化任何数据库对象。它们主要用于参数化WHERE / HAVING子句。
query = "select "+fieldName+" from "+tableName+" where "+conditionFieldName+" = ?;"
preparedStatement.setInt(1, conditionValue);