更有效的方法将值插入到mysql表中

use*_*791 0 java mysql

我有一个Collection,我想将Nodes的值写入mysql表.现在我连接到数据库,创建一个语句,然后为我运行的集合中的每个节点

// open the connection then
Statement statement = connect.createStatement();
for (Node n : vertices) {
   statement.execute("INSERT INTO " + table + " (name, department) values ('" + n.getName() + "', '" + n.getOrgId() + "')");
}
// then I close the connection
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更有效的方法来处理这样的任务.

Bar*_*nka 6

使用预备陈述:

String query = "insert into " + table + " (name, department) values (?,?)";
try(PreparedStatement ps = connection.prepareStatement(query)) {
    for(Node n : vertices) {
        ps.setString(1, n.getName());
        ps.setInt(2, n.getOrgId());
        ps.addBatch();
    }
    ps.executeBatch();
} catch(SQLException e) {
    // Exception handling
}
Run Code Online (Sandbox Code Playgroud)

请注意,由于构建查询的方式,它仍然容易受到SQL注入attac的影响(因为您正在使用变量构建字符串table).我建议您删除table变量或采取措施以确保程序的任何用户都不会看到该变量.