我正在编写一个使用本地 SQL 数据库来存储数据的程序。
我正在使用这里找到的驱动程序:https://bitbucket.org/xerial/sqlite-jdbc 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。
然而,当我尝试添加行时,它会导致异常:
java.sql.SQLException: database is locked
指向该行:
statement.executeUpdate(stmt);
...在 addRow() 方法中。
为什么数据库被锁定以及如何解锁才能写入?
为什么数据库被锁定以及如何解锁才能写入?
数据库很可能被锁定addRow
因为之前的调用getTable
没有关闭结果集。该代码还无法关闭数据库连接对象,这将导致资源泄漏。
基本的修复方法是调用close()
on the rs
and connection
对象,但您需要以正确的方式进行操作以使代码可靠。
以下是在 Java 7 中使用“try with resources”语法执行此操作的推荐方法:
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;
}
您也可以通过致电来做到这一点close
明确地在finally
块,但它更冗长,如果您有需要关闭的相关资源......就像这里一样,代码可能很难正确。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)