简体   繁体   English

带有变量的Java JDBC查询?

[英]Java JDBC Query with variables?

String poster = "user";

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM `prices` WHERE `poster`="+poster);

This does not work.Any tips or tricks would be appreciated. 这不起作用。任何提示或技巧将不胜感激。

Try surrounding the poster variable with single quotes, like this: 尝试使用单引号包围poster变量,如下所示:

ResultSet rs = stmt.executeQuery("SELECT * FROM `prices` WHERE `poster`='"+poster+"'");

That's because SQL expects strings to be surrounded by single quotes. 那是因为SQL期望字符串被单引号括起来。 An even better alternative would be to use prepared statements: 更好的选择是使用准备好的语句:

PreparedStatement stmt = con.prepareStatement("SELECT * FROM `prices` WHERE `poster` = ?");
stmt.setString(1, poster);
ResultSet rs = stmt.executeQuery();

It's recommended using PreparedStatement since the way you are currently building the query (by concatenating strings) makes it easy for an attacker to inject arbitrary SQL code in a query, a security threat known as a SQL injection . 建议使用PreparedStatement因为您当前构建查询的方式(通过连接字符串)使攻击者可以轻松地在查询中注入任意SQL代码,这是一种称为SQL注入的安全威胁。

您需要准备好的声明,请查看本教程。

1) In general, to "parameterize" your query (or update), you'd use JDBC "prepared statements": 1)通常,要“参数化”您的查询(或更新),您将使用JDBC“预编译语句”:

2) In your case, however, I think all you need to do is add quotes (and lose the back-quotes): 2)但是,在你的情况下,我认为你需要做的就是添加引号(并丢失后引号):

// This is fine: no back-quotes needed
ResultSet rs = stmt.executeQuery("SELECT * FROM prices");


// Since the value for "poster" is a string, you need to quote it:
String poster = "user";
Statement stmt = con.createStatement();
ResultSet rs = 
  stmt.executeQuery("SELECT * FROM prices WHERE poster='" + poster + "'");

The Statement interface only lets you execute a simple SQL statement with no parameters. Statement接口只允许您执行不带参数的简单SQL语句。 You need to use a PreparedStatement instead. 您需要使用PreparedStatement。

PreparedStatement pstmt = con.prepareStatement("
                          select * from 
                          prices where 
                          poster = ?");

pstmt.setString(1, poster);
ResultSet results = ps.executeQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM