我正在编写一个使用本地 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。
当我尝试添加该行时,它会导致异常:
java.sql.SQLException: database is locked
指向这条线:
statement.executeUpdate(stmt);
...在 addRow() 方法中。
为什么数据库被锁定,我如何解锁它以写入它?