[英]SQLITE_BUSY the database is locked java
我已經創建了一個使用sqlite數據庫的Java軟件。 整個數據庫運行正常,但是在運行應用程序一段時間后,我收到了以下消息(來自try catch塊):
java.sql.SQLException:[SQLITE_BUSY]數據庫文件被鎖定(數據庫被鎖定)
每次出現異常時,我都通過關閉軟件來解決問題。 但是,有沒有一種方法可以關閉我的數據庫,以免每次都不關閉軟件?
我有很多疑問,但是我的問題總是出現在特定的地方:
try {
String query = "select * from StudentsSession where userId=? and course=? and level=?";
PreparedStatement pst = connectionUsers.prepareStatement(query);
pst.setString(1, saveUser.getText());
pst.setString(2, textSubjectQTest);
st.setString(3, showCurrentLevelLabel.getText());
ResultSet rs = pst.executeQuery();
while (rs.next()) {
count = count + 1;
}
pst.close();
rs.close();
} catch (Exception a) {
System.out.println(a);
}
try {
String countS, tmpS;
countS = String.valueOf(count);
sessionId.setText(countS);
long unixTime = System.currentTimeMillis() / 1000L;
tmpS = String.valueOf(unixTime);
date.setText(tmpS);
course.setText(textSubjectQTest);
String query = "insert into StudentsSession (userId,date,course,level,trial,score) values (?,?,?,?,?,-1)";
PreparedStatement pst = connectionUsers.prepareStatement(query);
pst.setString(1, saveUser.getText());
pst.setString(2, tmpS);
pst.setString(3, textSubjectQTest);
pst.setString(4, showCurrentLevelLabel.getText());
pst.setString(5, countS);
pst.executeUpdate();
pst.close();
} catch (Exception a) {
System.out.println(a);
System.exit(0);
}
String file1 = "";
ResultSet ts4;
try {
sessionId3 = "";
String query3 = "select * from studentssession where userid = ? and course = ? and level = ?";
PreparedStatement pst__1 = connectionUsers.prepareStatement(query3);
pst__1.setString(1, saveUser.getText());
pst__1.setString(2, textSubjectQTest);
pst__1.setString(3, showCurrentLevelLabel.getText());
ts4 = pst__1.executeQuery();
while (ts4.next()) {
sessionId3 = ts4.getString("sessionId");
}
pst__1.close();
ts4.close();
obj = new CaptureVideoFromWebCamera();
file1 = "videos/" + userTextFieldS.getText();
file1 = file1 + "_" + sessionId3;
file1 = file1 + ".wmv";
obj.start(file1);
} catch (Exception e4) {
e4.getCause();
}
有時,此代碼會引發異常。
您的try catch錯誤,您嘗試在try塊而不是finally塊中關閉ResultSet
和Statemnt
。 這可能導致泄漏。
最后,您應該這樣做。
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = connectionUsers.prepareStatement(query);
...
rs = pst.executeQuery();
...
} catch (Exception a) {
a.printStackTrace();
} finally {
if(rs != null){
try{
rs.close();
} catch(Exception e){
e.printStackTrace();
}
}
if(pst != null){
try{
pst.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
或者,您可以嘗試使用資源。
這可能是一個原因。
對現有問題進行排序,但這是一個很好的起點 。 因為SQLite只是一個讀寫文件系統上文件的庫,而不是完整的SQL數據庫,所以實際上您一次只應該打開一個連接。 否則很容易進入比賽狀態。
對於本地測試,應該沒問題,但是對於期望有多個用戶的復雜性的系統,您應該使用Postgre或MySQL之類的東西。
每次您打開與SQLite數據庫的連接時,請確保在處理結果等之后關閉數據庫連接。如果您已經與數據庫建立了連接,並且嘗試重新獲取連接並嘗試執行某些Update
或Insert
查詢后,系統將不授予權限,並會引發錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.