我已将JDBC与PostgreSQL相关联。我们如何使用占位符创建视图?
但是我收到了这个错误:
SQL异常:错误:没有参数$ 1 Position: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();
)会导致异常。为什么呢?
答案 0 :(得分:0)
创建一个名为"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));
毋庸置疑,在这种情况下,清理用户输入非常重要。