JDBC - 准备语句 - 我应该如何使用它?
我在某处看到了这个例子:
rs = connection.prepareStatement("select * from table").executeQuery();
如果我想执行这样的查询“Select * from table where column = “hello””,我可以使用这种格式吗?
我通常使用prepareStatement对象的方式是这样的:
String sql = "select * from adresa where column = ?";
PreparedStatement pre = con.prepareStatement(sql);
pre.setString(1, i);
rs = pre.executeQuery();
稍后编辑:
我不明白。 Pascal Thivent 写道,我可以使用带 In 参数的简短版本,但 Liu 告诉我这是不可能的。 :) Anw,使用 Pascal 的版本,我收到此错误: void 无法取消引用
I saw this example somewhere:
rs = connection.prepareStatement("select * from table").executeQuery();
Could I use this format, if I want to execute a query like this "Select * from table where column = "hello" "?
The way in which I usual I use prepareStatement object is something like this:
String sql = "select * from adresa where column = ?";
PreparedStatement pre = con.prepareStatement(sql);
pre.setString(1, i);
rs = pre.executeQuery();
Later Edit:
I don't understand. Pascal Thivent wrote that I can use the short version with In parameters, but Liu tells me this is not possible. :) Anw, using Pascal's version, i receive this error: void cannot be dereferenced
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是如何使用此接口的部分示例:
Here's a partial example how to use this interface:
如果查询中没有绑定变量(问号),则只能使用第一种形式。这只是您发布的内容的缩短版本。
另外,如果您使用缩写形式,您将没有机会重用PreparedStatement 对象。
You can only use the first form if there are no bind variables (question marks) in the query. It's just a shortened version of what you posted.
Also, if you use the shortened form you won't have the opportunity to reuse the PreparedStatement object.
当然,您可以使用字符串变量进行查询,在其中输入动态数据并运行它。
rs = connection.prepareStatement(variable).executeQuery();
of course u can use a string variable for the query in which u put in ur dynamic data and run it.
rs = connection.prepareStatement(variable).executeQuery();
长格式很常见,但是准备好的语句可以由数据库预编译,如果使用得当将有助于防止 sql 注入。
谁说java很冗长。 :)
The long form is often, but prepared statements can be precompiled by the db, and if used properly will help prevent sql injection.
Who said java was verbose. :)