I've been trying to figure out why my prepared statement puts '
before and after my strings. When I try to use this code for my Postgressql database server I get an syntax error. This is because this program processes the code as following :
Imagine I call this method as follow:
selectStringQuery("username", "users", "id", 1);
Then the program returns the following prepared statement:
SELECT 'username' FROM 'users' WHERE 'id' = 1;
The following error occurs when i run the program :
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$2"
Position: 16
It should produce this:
SELECT username FROM users WHERE id = 1;
Could somebody please tell me what I'm missing here?
* 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;
}
}