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

标签 java

我已经开始学习 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/

相关文章:

java - JPA 和类路径

java - 小错误第10001个素数java代码?

java - H2 - 在 Java 中构建并执行查询以进行日期比较

java - 即使使用K_COMPILATION_UNIT和BindingRecovery,Eclipse AST方法resolveTypeBinding也始终为空

java - ShutdownHook 代码未在 System.exit(0) 上执行

java - 从具有特定值的 clojure vector 中提取 HashMap 列表

java - 执行代理查找时出现重复 session 错误

java - 在 Unirest 中获取 native REST 服务错误

java - Java Scanner 输入和 while 循环出现问题,其中包含多个 if 语句

java - 查找二维数组中数字的位置