如何在没有硬编码值的情况下编写此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...
提前致谢..
以您当前的方式构建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();
}