gpt4 book ai didi

java - 将动态变量实现到 SQL 语句中时,有没有比字符串连接更好的方法

转载 作者:搜寻专家 更新时间:2023-10-30 20:08:34 26 4
gpt4 key购买 nike

我在 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 语句放在一起是有风险的,而且我想知道获得相同结果的替代方法。

最佳答案

一个好的替代方法是使用 prepared statements :例子

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)

关于java - 将动态变量实现到 SQL 语句中时,有没有比字符串连接更好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37156169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com