我有一個軟件,一次由2個用戶使用,他們在幾個步驟中一起交互。有時一個用戶必須等待另一個用戶,直到他將數據插入數據庫。然後再次檢索相同的數據。
令人困惑的是,有時我會在不更改代碼的情況下接收所有數據,有時僅接收部分數據,有時甚至不接收數據庫。
是否有可能,我只是檢索它「太快」?插入後檢索毫秒。也許數據庫需要一些時間來進行操作。
如果是這樣,是否有可能收到類似「成功消息」的東西,是否插入了所有內容?MySQL:運行後返回成功
這是插入功能。它在循環內多次調用並插入一些數據。之後,更新標誌準備在另一個表:
public void insert(String name, int id) {
try {
stmt = conn.prepareStatement("INSERT INTO user(name) VALUES (?)");
stmt.setString(1, name);
stmt.executeUpdate();
stmt = conn.prepareStatement("UPDATE session set ready = 1 WHERE id = ?");
stmt.setInt(1, id);
stmt.executeUpdate();
stmt.close();
} catch (SQLException ex) {
System.err.println(ex);
}
}
然後,這些功能都檢查每一個第二,如果從其他用戶的標誌準備尚未確定。
timer.schedule(new TimerTask() {
@Override
public void run() {
if (DB.INSTANCE.check(5)) {
// retrieving data from database...
timer.cancel();
}
}
}, 0, 1000);
如果設置了標誌,則返回真及以上,則函數再次檢索數據。
public boolean check(int id) {
boolean notify = false;
try {
stmt = conn.prepareStatement("SELECT * FROM session WHERE id = ?");
stmt.setString(1, id);
stmt.executeQuery();
while (stmt.getResultSet().next()) {
if (stmt.getResultSet().getInt("ready") == 1) {
notify = true;
}
}
stmt.close();
} catch (SQLException ex) {
System.err.println(ex);
}
return notify;
}
這是我迄今爲止的解決方案,如上所述,這不幸不起作用。
編輯
當標誌設置該功能被稱爲:
public void load() {
data= DB.INSTANCE.loadChosen(id);
if (data.isEmpty()) {
model.addElement("Nothing!");
} else {
for (Map.Entry e : data.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
model.addElement(e.getKey());
}
}
}
它被literated並放入模型(JList的)。
這是在數據庫類中的相應功能:檢索
public HashMap load(int id) {
try {
stmt = conn.prepareStatement("SELECT * FROM users WHERE id LIKE ?");
stmt.setString(1, id);
stmt.executeQuery();
while (stmt.getResultSet().next()) {
String name = stmt.getResultSet().getString("name");
int coe1 = stmt.getResultSet().getInt("coe1");
chosenNames.put(name, coe1);
}
stmt.close();
} catch (SQLException ex) {
System.err.println(ex);
}
return data;
}
的實際數據是不是真的很重要,這些都只是名字和號碼,一切都放在一個HashMap。
當我在控制檯中返回數據時,有時甚至會丟失一些數據,儘管它們在數據庫中。
出於興趣,您使用的是什麼事務隔離級別? – Neil
對不起,我從來沒有聽說過... – user1170330
'id'是'session'的主鍵嗎?你能提供你在兩種情況下得到的數據樣本嗎? –