JDBC SQL数据库被锁定了吗?

我正在编写一个使用本地SQL数据库来存储数据的程序。

我正在使用此处找到的驱动程序: https : //bitbucket.org/xerial/sqlite-jdbc

我试图从数据库中读取并将tableName的内容放入JTable中,如下所示:

public Object[][] getTable(String tableName){ int columns = getColumnNumber(tableName); int rows = getRowNumber(tableName); String[] columnNames = getColumnNames(tableName); Object[][] table = new Object[rows][columns]; try{ Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbName + ".db"); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from " + tableName); for(int r = 0; r < rows; r++){ rs.next(); for (int c = 0; c < columns; c++){ table[r][c] = rs.getString(columnNames[c]); } } return table; }catch(Exception e){ System.out.println("ERROR CREATING TABLE ARRAY"); e.printStackTrace(); return null; } } 

然后我尝试回来并在表格中添加一行:

 public boolean addRow(String tableName, Object[] values){ if(!isDataAcceptable(tableName, values)) return false; try{ String stmt = "insert into " + tableName + " values ("; for(int c = 0; c < values.length; c++){ if(values[c] instanceof String) stmt += "'" + values[c] + "'"; else stmt += values[c]; if(c == (values.length - 1)) stmt += ");"; else stmt += ", "; } System.out.println(stmt); Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbName + ".db"); Statement statement = connection.createStatement(); statement.executeUpdate(stmt); return true; }catch(Exception e){ System.out.println("ERROR INSERTING ROW"); e.printStackTrace(); return false; } } 

然后我想用新行更新我之前创建的JTable。

当我尝试添加行但它会导致exception:

 java.sql.SQLException: database is locked 

指向该行:

 statement.executeUpdate(stmt); 

…在addRow()方法中。

为什么数据库已锁定,如何解锁以写入数据库?

为什么数据库已锁定,如何解锁以写入数据库?

数据库很可能在addRow被锁定,因为之前对getTable调用没有关闭结果集。 代码也无法关闭将导致资源泄漏的数据库连接对象。

基本的解决方法是在rsconnection对象上调用close() ,但是你需要以正确的方式来使代码可靠。

以下是使用“try with resources”语法在Java 7中执行此操作的推荐方法:

 try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbName + ".db"), Statement stmt = connection.createStatement(), ResultSet rs = stmt.executeQuery("select * from " + tableName)) { for (int r = 0; r < rows; r++) { rs.next(); for (int c = 0; c < columns; c++) { table[r][c] = rs.getString(columnNames[c]); } } return table; } catch (Exception e) { System.out.println("ERROR CREATING TABLE ARRAY"); e.printStackTrace(); return null; } 

您也可以通过在finally块中显式调用close来完成此操作,但它更详细,如果您有相关的资源需要关闭,代码可能很难正确...就像这里一样。