java编写的语句,字符串卡在引号中

plicqrtu  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(346)

我一直在想为什么我准备的声明 ' 在我的琴弦前后。当我尝试将此代码用于我的postgressql数据库服务器时,我得到了一个语法错误。这是因为此程序按以下方式处理代码:
假设我将此方法称为:

  1. selectStringQuery("username", "users", "id", 1);

然后程序返回以下准备好的语句:

  1. SELECT 'username' FROM 'users' WHERE 'id' = 1;

运行程序时出现以下错误:

  1. org.postgresql.util.PSQLException: ERROR: syntax error at or near "$2"
  2. Position: 16

它应该产生:

  1. SELECT username FROM users WHERE id = 1;

有人能告诉我我错过了什么吗?

  1. * Executes a select query.
  2. * @param selectFieldName
  3. * @param tableName
  4. * @param conditionFieldName
  5. * @param conditionValue
  6. * @return
  7. */public String selectStringQuery(String selectFieldName, String tableName, String conditionFieldName, int conditionValue){
  8. try {
  9. //***Start execution of query***
  10. query = "SELECT ? FROM ? WHERE ? = ?;";
  11. preparedStatement = prepareStatement(query);
  12. preparedStatement.setString(1, selectFieldName);
  13. preparedStatement.setString(2, tableName);
  14. preparedStatement.setString(3, conditionFieldName);
  15. preparedStatement.setInt(4, conditionValue);
  16. System.out.println(preparedStatement);
  17. resultSet = preparedStatement.executeQuery();
  18. //***End execution of query***
  19. //***Start validity checks***
  20. if(!resultSet.next()){
  21. System.out.println("Query did not return any results.");
  22. return null;
  23. }
  24. //***End validity checks***
  25. //***Start process query results***
  26. String result = resultSet.getString(selectFieldName);
  27. return result;
  28. //***End process query results***
  29. } catch (Exception ex) {
  30. System.out.println(ex);
  31. return null;
  32. }
  33. }
wdebmtf2

wdebmtf21#

尝试在查询字符串中包含表名和列名。

  1. query = "SELECT "+selectFieldName+" FROM "+tableName+" WHERE "+conditionFieldName+" = ?;";

我认为不能将表名和列名作为参数传递。参数被视为列值和 '' 添加到它们中

wz1wpwve

wz1wpwve2#

你可以试试这样的

  1. query = "SELECT "+selectFieldName+" FROM "+tableName+" WHERE "+selectFieldName+" = ?;"
8fq7wneg

8fq7wneg3#

参数不能用于参数化表或任何数据库对象。它们主要用于参数化where/having子句。

  1. query = "select "+fieldName+" from "+tableName+" where "+conditionFieldName+" = ?;"
  2. preparedStatement.setInt(1, conditionValue);

相关问题