簡體   English   中英

如何插入清單 <String[]> 使用JDBC將數據導入數據庫?

[英]How to insert List<String[]> data into database using JDBC?

我的List<String[]>的當前格式為:

60 52 0 0 1512230400
76 52 1 1 1514044800 
42 52 4 1 1516464000

因此,每個用空格分隔的值在我的數據庫表中都是一行,例如: 60 52 0 0 1512230400 我想在每個循環中插入5個單獨的值。 我想將所有這些行插入到數據庫中,但不確定確切的方式。 到目前為止,這也是與我的數據庫的有效連接。

這是我的粗略想法:

String query = "INSERT INTO games (team1_id, team2_id, score1, score2, created_at) VALUES (? ,?, ?, ?, ? )";
Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query);//prepare the SQL Query

for (String[] s : fixtures) {

}

任何幫助都是驚人的。

非常感謝

在for循環中,您可以執行以下操作:

stmt.setString(1, s[0]); //team1_id if it's of string type in db
stmt.setInt(2, Integer.parseInt(s[1])); //team2_id if it's of type integer in db
stmt.setInt(3, Integer.parseInt(s[2])); //score1
stmt.setInt(4, Integer.parseInt(s[3])); //score2
stmt.setLong(5, Long.parseLong(s[4])); //created_at
stmt.executeUpdate();

上面的代碼展示了如何處理String,Long和Integer,您可以類似地使用其他類型。

List<String[]> fixtures = new ArrayList<>();
fixtures.add(new String [] {"60","52","0","0","1512230400"});
fixtures.add(new String [] {"76","52","1","1","1514044800"});
fixtures.add(new String [] {"42","52","4","1","1516464000"});

String query = 
  "INSERT INTO games (team1_id, team2_id, score1, score2, created_at)\n"
  + " VALUES (? ,?, ?, ?, ? )";
try(
  Connection con = DBConnector.connect();
  PreparedStatement stmt = con.prepareStatement(query);
) {
  for (String[] s : fixtures) {
    stmt.setString(1,s[0]);
    stmt.setString(2,s[1]);
    stmt.setString(3,s[2]);
    stmt.setString(4,s[3]);
    stmt.setString(5,s[4]);
    stmt.execute();
  }
  con.commit();
}

通過這種方法,我們將綁定變量作為字符串傳遞。 如果需要,數據庫將根據插入的列的實際類型,將字符串(VARCHAR)轉換為數字(NUMBER)。

您基本上都對了,但是並沒有采取下一步實際設置綁定變量的步驟

如果已經創建了輸入List那么這可以工作:

List<String[]> fixtures = ...; // assuming this data is already created
String query = "INSERT INTO games (team1_id, team2_id, score1, score2, created_at) VALUES (? ,?, ?, ?, ? )";

try (Connection con = DBConnector.connect();
      PreparedStatement stmt = con.prepareStatement(query)) {

    for (String [] row : fixtures) {

        // This gets executed for each row insert
        for (int i = 0; i < row.length; i++) {
            stmt.setInt(i+1, Integer.parseInt(row[i]);
        }

        stmt.executeUpdate();
    }
}
catch(SQLException ex) {
    ex.printStackTrace();
    // code that handles exception...
}

暫無
暫無

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

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