簡體   English   中英

Java JDBC多次插入和一般最佳實踐

[英]Java JDBC Multiple Insert and General Best Practises

我已經開始學習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)

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM