我有一个集合,我想将节点的值写入 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
我想知道是否有更有效的方法来处理这样的任务。
最佳答案
使用准备好的语句:
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
}
请注意,由于查询的构建方式,它仍然容易受到 SQL 注入(inject)攻击(因为您正在使用变量 table
构建字符串)。我建议您要么删除 table
变量,要么采取措施确保您的程序的任何用户永远不会看到该变量。
关于java - 将值插入 mysql 表的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24413894/