我正在編寫一個Java API,並且正在使用MySQL。線程安全讀取和寫入數據庫的最佳做法是什麼?如何線程安全地讀取和寫入數據庫?
例如,採取以下createUser
方法:
// Create a user
// If the account does not have any users, make this
// user the primary account user
public void createUser(int accountId) {
String sql =
"INSERT INTO users " +
"(user_id, is_primary) " +
"VALUES " +
"(0, ?) ";
try (
Connection conn = JDBCUtility.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
int numberOfAccountsUsers = getNumberOfAccountsUsers(conn, accountId);
if (numberOfAccountsUsers > 0) {
ps.setString(1, null);
} else {
ps.setString(1, "y");
}
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Get the number of users in the specified account
public int getNumberOfAccountsUsers(Connection conn, int accountId) throws SQLException {
String sql =
"SELECT COUNT(*) AS count " +
"FROM users ";
try (
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
return rs.getInt("count");
}
}
說源A調用createUser
,和剛剛讀該帳戶ID 100具有0個用戶。然後,源B調用createUser
,並且在源A執行更新之前,源B也讀取了該帳戶ID具有0個用戶。結果,源A和源B都創建了主要用戶。
這種情況如何安全實施?
所以這個問題實際上與線程安全無關。這是你真正的問題還是你用它來解釋你的問題?另外,你正在使用什麼數據庫系統(MySQL,SQL Server等)? –
他/她已經提到了MySQL – Ele
順便說一句,您如何在第二種方法中使用'accountId'? –