【问题标题】:Why this JDBC statement causes an exception?为什么这个 JDBC 语句会导致异常?
【发布时间】:2016-03-14 15:29:48
【问题描述】:

我已将 JDBC 与 PostgreSQL 链接。我们如何使用占位符创建视图?

但我收到此错误:

SQL 异常:错误:没有参数 $1 位置:72

queryString = "CREATE VIEW clients AS (SELECT client_id FROM Client WHERE firstname = ?)";
pStatement = conn.prepareStatement( queryString );

System.out.println("Enter the name of a client");
br = new BufferedReader( new InputStreamReader(System.in) );
String client_name = br.readLine();

pStatement.setString(1, client_name);
pStatement.executeUpdate();

最后一行 (pStatement.executeUpdate();) 导致异常。为什么?

【问题讨论】:

  • 不确定在创建查询中是否会正确考虑占位符。查看此主题并尝试打印最终查询,以了解在您的 setString 之后语句的实际外观。 stackoverflow.com/questions/2683214/…
  • 您无法创建带有参数的视图(顺便说一句:create view 的选择周围的括号完全没用)

标签: java postgresql jdbc


【解决方案1】:

创建一个名为 "clients" 的视图来过滤客户端子集似乎并不可取 - 您确定不只是想要一个准备好的语句,而不是一个视图吗?

如果您确实想动态创建视图,则需要在 Java 中构造 SQL(DDL 语句不能参数化):

String queryString = "CREATE VIEW \"clients_named_%1$s\" AS (SELECT client_id FROM client WHERE firstname = '%1$s')";

System.out.println("Enter the name of a client");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String clientName = br.readLine();

// sanitize in a way that makes sense for your data
clientName = clientName.replaceAll("\\W", "");

Statement stmt = conn.createStatement();
stmt.executeUpdate(String.format(queryString, clientName));

不用说,在这种情况下清理用户输入很重要。

【讨论】:

    猜你喜欢
    • 2015-05-15
    • 1970-01-01
    • 2015-06-12
    • 2012-01-09
    • 2012-04-20
    • 1970-01-01
    • 2014-11-07
    • 2011-01-13
    • 2018-07-10
    相关资源
    最近更新 更多