Java – SQL SELECT statement with where clause

How do I write this SQL statement without a hard coded value?

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

But something similar:

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...

Thank you in advance

Solution

Building SQL queries in your current way is usually a bad idea because it opens the door to various SQL injection attacks To perform this operation correctly, you must use prepared statements This will also solve all kinds of evasion problems that are obvious to you at present

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

Note that preparestatement () is an expensive call (unless your application server uses statement caching and other similar tools) In theory, it is best to prepare a statement once and then reuse it many times (although not at the same time):

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();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>