public class SqlExeTest {
@Test
public void test() throws InterruptedException {
Connection conn = null;
Connection conn2 = null;
String url = "jdbc:mysql://localhost:3306/TODO db name"; //TODO
String user = "TODO user";//TODO
String password = "TODO pass";//TODO
try {
conn = DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false);
conn2 = DriverManager.getConnection(url, user, password);
conn2.setAutoCommit(false);
Statement stmt = conn.createStatement();
Statement stmt2 = conn2.createStatement();
int preid = selectMaxId(stmt);
int id = preid;
for (; id < preid + 5; id++) {
exeSql(stmt, id);
Thread.sleep(1000 * 2);
if (conn.getAutoCommit() == false) {
System.out.println("commit");
conn.commit();
}
selectCount(stmt2);
if (conn2.getAutoCommit() == false) {
System.out.println("commit2");
conn2.commit();
}
selectCount(stmt2);
Thread.sleep(1000 * 2);
}
} catch (SQLException e) {
// exception
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// exception
}
}
}
void exeSql(Statement stmt, int id) throws SQLException {
String sql = "INSERT INTO tbl_status ( id, del, ins, upd, version, memo, name, sort ) VALUES "//
+ "(" + id + ",null,'2022-02-19 19:53:03','2022-03-07 21:04:51',2,null,'test',5);";
System.out.println("insert");
int count = stmt.executeUpdate(sql);
System.out.println("ins count = " + count);
}
int selectMaxId(Statement stmt) throws SQLException {
String sql = "select max(id) from tbl_status";
ResultSet rs = stmt.executeQuery(sql);
int idMax = 0;
if (rs.next()) {
idMax = rs.getInt(1);
}
return idMax + 1;
}
void selectCount(Statement stmt) throws SQLException {
String sql = "select count(*) from tbl_status";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
System.out.println("count = " + rs.getInt(1));
} else {
System.out.println("count = " + 0);
}
}
}