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

时间:2014-06-30 22:28:01

标签: 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

1 个答案:

答案 0 :(得分:2)

您可以在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)

希望有所帮助