[英]Java JDBC Multiple Insert and General Best Practises
I have started to learn the JDBC as i want a plugin i am creating to connect with a database, i have it working right now but one thing i don't like is i have an insert query within a for loop which of course is bad. 我已经开始学习JDBC,因为我想创建一个插件来与数据库连接,我现在可以正常使用它,但是我不喜欢的一件事是我在for循环中有一个插入查询,这当然是不好的。 How would i achieve the same thing but with only one query?
只有一个查询,我将如何实现相同的目的? and also is the rest of my queries okay as in practise wise
在实践中我的其余询问也可以吗
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
You can use updateBatch on the Statement/PreparedStatement- this way, you can batch the inserts into the database instead of sending in so many inserts into the database as separate jobs. 您可以在Statement / PreparedStatement上使用updateBatch-这样,您可以将插入内容批处理到数据库中,而不是将那么多插入内容作为单独的作业发送到数据库中。
For instance: 例如:
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)
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.