我在 Java 工作,我有以下方法:
public ResultSet getRecordsWithinBoundingBox(int spillFarLeftValue, int spillFarRightValue, int spillMostDownwardValue, int spillMostUpwardValue) { ResultSet resultSet = null; try { Statement statement = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql = "SELECT * FROM OTH WHERE (jl<=" + spillMostUpwardValue + " AND (ih>=" + spillFarLeftValue + " AND ih<=" + spillFarRightValue+ ") OR (il<=" + spillFarRightValue + " AND il>=" + spillFarLeftValue + ")) OR (jh>=" + spillMostDownwardValue + " AND (ih>=" + spillFarLeftValue + " AND ih<=" + spillFarRightValue + ") OR (il<=" + spillFarRightValue + " AND il>=" + spillFarLeftValue + ")) OR (il<=" + spillFarLeftValue + " AND ih>=" + spillFarRightValue + " AND (jl<=" + spillMostUpwardValue + " AND jl>=" + spillMostDownwardValue + ") OR (jh>=" + spillMostDownwardValue + " AND jh>=" + spillMostUpwardValue + ")) OR (jl<=" + spillMostDownwardValue + " AND jh>=" + spillMostUpwardValue + " AND (il>=" + spillFarLeftValue + " AND il<=" + spillFarRightValue + ") OR (ih<=" + spillFarRightValue + " AND ih>=" + spillFarLeftValue + ")) OR (il<=" + spillFarLeftValue + " AND ih>=" + spillFarRightValue + " AND jl<=" + spillMostDownwardValue + " AND jh>=" + spillMostUpwardValue + ")"; resultSet = statement.executeQuery(sql); statement.close( ); resultSet.close( ); } catch (SQLException ex) { Logger.getLogger(DatabaseInteractor.class.getName()).log(Level.SEVERE, null, ex); } return resultSet; }
如您所见,我目前正在使用一个巨大的字符串从我的数据库中提取数据,但有人告诉我这不是最好的解决方案。但遗憾的是,我也没有被告知我应该做什么。但是我觉得以我现在的方式组合 SQL 语句是有风险的,而且我想知道获得相同结果的替代方法。
一个很好的选择是使用准备好的语句:示例
sql= "INSERT INTO imt_database.Comment(error_id,user,content) VALUES (?,?,?);"; try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(URL,"root","toor"); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, Error_id); ps.setString(2, User); ps.setString(3, Content); ps.executeUpdate(); }catch(Exception e)