gpt4 book ai didi

Java JDBC 多重插入和一般最佳实践

转载 作者:行者123 更新时间:2023-12-02 05:41:15 25 4
gpt4 key购买 nike

我已经开始学习 JDBC,因为我想要一个正在创建的插件来连接数据库,我现在可以使用它,但我不喜欢的一件事是我在 for 循环中有一个插入查询,其中当然是不好的。我如何通过一个查询实现同样的目标?我的其余查询在实践中也可以吗

open(); // opens a connection from a method
try{
PreparedStatement sql = con.prepareStatement("INSERT INTO `score` (player, score) VALUES (?,?);");
sql.setString(1, "test");
sql.setInt(2, 1);
sql.execute();
sql.close();
}catch(Exception e){
e.printStackTrace();
}

try{
PreparedStatement s = con.prepareStatement("SELECT COUNT(*) AS rowcount FROM score"); // get the number of rows
ResultSet r = s.executeQuery();
r.next();
int count = r.getInt("rowcount") / 2; // divide total rows by 2
int q = Math.round(count);
r.close();
s.close();
PreparedStatement ss = con.prepareStatement("SELECT id FROM score ORDER BY score DESC LIMIT ?;"); // get the top half of results with the highest scores
ss.setInt(1, q);
ResultSet rs = ss.executeQuery();

while(rs.next()){
PreparedStatement qq = con.prepareStatement("INSERT INTO `round2` (player, score) VALUES (?,?);"); //this is the insert query
qq.setString(1, rs.getString("player"));
qq.setInt(2, 0);
qq.execute();
qq.close();
}

rs.close();
ss.close();
}catch(Exception e){
e.printStackTrace();
}
close(); //close connection

最佳答案

您可以在 Statement/PreparedStatement 上使用 updateBatch - 这样,您可以批量将插入插入到数据库中,而不是将如此多的插入作为单独的作业发送到数据库中。

例如:

import java.sql.Connection;
import java.sql.PreparedStatement;

//...

String sql = "insert into score (player, score) values (?, ?)";
Connection connection = new getConnection(); //use a connection pool
PreparedStatement ps = connection.prepareStatement(sql); //prefer this over statement

for (Player player: players) { //in case you need to iterate through a list

ps.setString(1, player.getName()); //implement this as needed
ps.setString(2, player.getScore()); //implement this as needed
ps.addBatch(); //add statement to batch
}
ps.executeBatch(); //execute batch
ps.close(); //close statement
connection.close(); //close connection (use a connection pool)

希望对你有帮助

关于Java JDBC 多重插入和一般最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24499888/

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