java – 带有where子句的SQL select语句
发布时间:2020-12-15 02:07:18 所属栏目:Java 来源:网络整理
导读:如何在没有硬编码值的情况下编写此sql语句? resultSet = statement .executeQuery("select * from myDatabase.myTable where name = 'john'");// this works 而是有类似的东西: String name = "john"; resultSet = statement .executeQuery("select * from
如何在没有硬编码值的情况下编写此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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |