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

时间:2019-02-19 23:42:00

标签: java for-loop jdbc insert prepared-statement

我的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) {

}

任何帮助都很棒。

非常感谢

3 个答案:

答案 0 :(得分:2)

在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,您可以类似地使用其他类型。

答案 1 :(得分:2)

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 ...

答案 2 :(得分:0)

如果已经创建了输入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...
}