带有where子句的SQL select语句

时间:2013-01-28 15:16:51

标签: java sql mysqli

如何在没有硬编码值的情况下编写此sql语句?

resultSet = statement
    .executeQuery("select * from myDatabase.myTable where name = 'john'");
// this works

更像是:

String name = "john"; 
resultSet = statement
    .executeQuery("select * from myDatabase.myTable where name =" + name);
// Unknown column 'john' in 'where clause' at
// sun.reflect.NativeConstructorAccessorImpl.newInstance0...etc...

提前感谢..

6 个答案:

答案 0 :(得分:20)

以您当前的方式构建SQL查询通常是一个糟糕的主意,因为它为各种SQL注入攻击打开了大门。要正确执行此操作,您必须使用Prepared Statements。这也将解决您目前显而易见的各种逃避问题。

PreparedStatement statement = connection.prepareStatement("select * from myDatabase.myTable where name = ?");    
statement.setString(1, name);    
ResultSet resultSet = statement.executeQuery();

请注意,prepareStatement()是一项昂贵的调用(除非您的应用程序服务器使用语句缓存和其他类似工具)。从理论上讲,最好是准备一次语句,然后多次重复使用它(虽然并发):

String[] names = new String[] {"Isaac", "Hello"};
PreparedStatement statement = connection.prepareStatement("select * from myDatabase.myTable where name = ?");

for (String name: names) {
    statement.setString(1, name);    
    ResultSet resultSet = statement.executeQuery();
    ...
    ...
    statement.clearParameters();
}

答案 1 :(得分:4)

您缺少字符串周围的单引号,您的代码已更正:

String name = "john";
String sql = "select * from myDatabase.myTable where name = '" + name + "'";
// Examine the text of the query in the debugger, log it or print it out using System.out.println
resultSet = statement.executeQuery(sql);

在执行查询之前打印/记录查询文本以查看它是否正常。

如果您要进行大量类似的查询,只有常数变化,请考虑使用prepared statements

答案 2 :(得分:1)

这应该有效:

String name = "john"; 
resultSet = statement
    .executeQuery("select * from myDatabase.myTable where name =" + "'" + name + "'");

答案 3 :(得分:0)

你需要在值周围加上引号('john'而不是john)......

答案 4 :(得分:0)

尝试以下方法:

String name = "john"; 

resultSet = statement
      .executeQuery("select * from myDatabase.myTable where myTable.name = '" + name + "'");

答案 5 :(得分:-1)

name值附近加上引号,因为它是一个字符串。

"select * from myDatabase.myTable where name ='" + name + "'"