Skip to content

Instantly share code, notes, and snippets.

@wqlin
Created October 27, 2018 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wqlin/e957e01fcb40986996b71831a4c45404 to your computer and use it in GitHub Desktop.
Save wqlin/e957e01fcb40986996b71831a4c45404 to your computer and use it in GitHub Desktop.
Read Committed Test
class MyRunner implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + ":连接数据库...");
Connection connection = null;
try {
connection = DriverManager.getConnection(RepeatableRead.DB_URL, RepeatableRead.USER, RepeatableRead.PASS);
connection.setAutoCommit(false);
//connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
String querySql = "select * from account where id=?";
synchronized (this) {
PreparedStatement queryStmt = connection.prepareStatement(querySql);
queryStmt.setInt(1, 1);
ResultSet set = queryStmt.executeQuery();
set.next();
int amount = set.getInt("amount");
System.out.println(Thread.currentThread().getName() + ":Amount=" + amount);
Thread.sleep(1000);
// 读取了数据,未提交事务。
String updateSql = "update account set amount=? where id=1";
PreparedStatement updateStmt = connection.prepareStatement(updateSql);
updateStmt.setInt(1, amount + 100);
int count = updateStmt.executeUpdate();
if (count > 0) {
set = queryStmt.executeQuery();
set.next();
amount = set.getInt("amount");
System.out.println(Thread.currentThread().getName() + ":更新成功...|" + amount);
}
connection.commit();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment