gpt4 book ai didi

java - 哪种方式更新数据库记录更好?

转载 作者:行者123 更新时间:2023-12-01 17:21:40 25 4
gpt4 key购买 nike

我有两种更新方法:

String query = "update mytable set name = 'new_value' where id ='20' ";
Connection conn;
PreparedStatement pState;
try {
conn = DriverManager.getConnection(dbUrl, "root", "2323");
pState = conn.prepareStatement(query);
pState.executeUpdate();
} catch (SQLException sql) {
sql.printStackTrace();
}

或者:

String query = "update mytable set name = ?" + "where id = ?";
Connection conn;
PreparedStatement pState;
int s;
try {
conn = DriverManager.getConnection(dbUrl, "root", "2323");
pState = conn.prepareStatement(query);
pState.setStringt(1, "new_value");
pState.setString(2, "20");
s = pState.executeUpdate(); // if s = 1 then update done successfully
} catch (SQLException sql) {
sql.printStackTrace();
}

两种方法都能正确更新数据库记录,哪个更好?

最佳答案

第二种方法是避免 S QL Injection attacks 的好习惯.

下面足以构造查询字符串,不需要另一个 + 连接。

 String query = "update mytable set name = ? where id = ?";

关于java - 哪种方式更新数据库记录更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18323277/

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