我的代码是一分钟存储一次数据,但我在数据库10分钟后才查到了数据,是什么原因。
按代码逻辑,我想每分钟数据库都应该有新增数据可以被查到的
main方法主要代码
while(i<10){
save(students,"students");
Thread.sleep(60000);
i++;
}
//存储数据的方法
public static void save(List<Student> students, String tableName) {
String sql = "INSERT INTO " + tableName
+ "(name)VALUES(?)";
MyConnection db = new MyConnection();
try {
db.conn.setAutoCommit(false);
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
for (int i = 0; i < students.size(); i++) {
Student student = students.get(i);
preStmt.setString(1, student.getName());
preStmt.addBatch();
}
preStmt.executeBatch();
preStmt.close();
db.close();// 关闭连接
} catch (Exception e) {
e.printStackTrace();
}
因为你写了preStmt.addBatch();这条语句是先把你的十条语句逐条加入缓冲区中,最后preStmt.executeBatch();一次性提交调用执行,所以你才会在十分钟之后看到