如何使用 JDBC 将 List<String[]> 数据插入数据库?

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

其中每个由 space 分隔的值在我的数据库 table 中是一行,例如: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) 的转换。

你基本上都做对了,但实际上没有采取下一步 setting the bind-variables ...

如果输入 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...
}