在操作SQLite Memory database时,遇到了奇怪的Exception – “[SQLITE_LOCKED] A table in database is locked (database table is locked)”. 检查之后才发现,原来是因为某些Statement在使用完成后,没有被关闭。这样导致Table锁住,后续的操作无法进行。
所以,Statement在使用完成后,一定要在finally里关闭,下面是段标准代码(异常处理的部分略)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Statement st = null; try { st = connection.createStatement(); ResultSet res = st.executeQuery("SELECT COUNT(*) FROM " + tableName); if (res.next()) { return res.getInt(1); // if there is result, get the result in first column } else { return -1; } } finally { if (st != null) { st.close(); } } |
写代码真要一丝不苟啊!