我已经创建了一个java软件,它利用sqlite数据库。但是,在运行应用程序的一段时间后,整个数据库运行得很顺利,我正在驳斥以下消息(来自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();
}有时,这段代码会引发异常。
发布于 2016-09-15 14:01:04
尝试捕获错误,尝试关闭try块中的ResultSet和Statemnt,而不是finally块。这可能会导致泄漏。
你应该这样做,在最后。
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();
}
}
}或者你可以用资源来尝试。
这可能是个原因。
发布于 2019-05-07 09:16:13
每次打开与SQLite数据库的连接时,如果您已经打开到数据库的连接,并且尝试再次获得连接并尝试某些Update或Insert查询,请确保在处理结果等之后关闭数据库连接,系统将不会授予权限并引发错误。
发布于 2016-09-15 12:11:51
重复现有的问题,但this is a good starting point。因为SQLite只是一个读取和写入文件系统上的文件的库,而不是一个完整的SQL数据库,所以实际上一次只能打开一个连接。否则很容易进入比赛状态。
对于本地测试,应该是可以的,但是对于任何复杂的系统,需要多个用户,您应该使用类似Postgre或MySQL之类的东西。
https://stackoverflow.com/questions/39510409
复制相似问题