下載 SQLite 的 JDBC 驅動 jar(例如 sqlitejdbc-v56.jar),加入 Java 專案的 classpath 即可,不需要額外安裝伺服器——SQLite 本身就是嵌進應用程式裡的資料庫。
直接用 JDBC 寫 SQL 很容易漏掉資源的釋放。下面這個 SqliteHelper 把連線、Statement、ResultSet 的生命週期收攏在一起,並用兩個策略介面把「結果集怎麼轉成物件」交給呼叫端決定,概念上近似 Spring JDBC 的 RowMapper。
public class SqliteHelper {
final static Logger logger = LoggerFactory.getLogger(SqliteHelper.class);
private Connection connection;
private Statement statement;
private ResultSet resultSet;
private String dbFilePath;
/** @param dbFilePath sqlite 檔案路徑 */
public SqliteHelper(String dbFilePath)
throws ClassNotFoundException, SQLException {
this.dbFilePath = dbFilePath;
connection = getConnection(dbFilePath);
}
/** 取得資料庫連線 */
public Connection getConnection(String dbFilePath)
throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
return DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);
}
/** 查詢並交由 ResultSetExtractor 自行處理整個結果集 */
public <T> T executeQuery(String sql, ResultSetExtractor<T> rse)
throws SQLException, ClassNotFoundException {
try {
resultSet = getStatement().executeQuery(sql);
return rse.extractData(resultSet);
} finally {
destroyed();
}
}
/** 查詢並逐列映射成物件清單 */
public <T> List<T> executeQuery(String sql, RowMapper<T> rm)
throws SQLException, ClassNotFoundException {
List<T> rsList = new ArrayList<T>();
try {
resultSet = getStatement().executeQuery(sql);
while (resultSet.next()) {
rsList.add(rm.mapRow(resultSet, resultSet.getRow()));
}
} finally {
destroyed();
}
return rsList;
}
/** 執行單條更新語句,回傳受影響列數 */
public int executeUpdate(String sql)
throws SQLException, ClassNotFoundException {
try {
return getStatement().executeUpdate(sql);
} finally {
destroyed();
}
}
/** 批次執行多條更新語句 */
public void executeUpdate(String... sqls)
throws SQLException, ClassNotFoundException {
try {
for (String sql : sqls) {
getStatement().executeUpdate(sql);
}
} finally {
destroyed();
}
}
public void executeUpdate(List<String> sqls)
throws SQLException, ClassNotFoundException {
try {
for (String sql : sqls) {
getStatement().executeUpdate(sql);
}
} finally {
destroyed();
}
}
private Connection getConnection()
throws ClassNotFoundException, SQLException {
if (null == connection) connection = getConnection(dbFilePath);
return connection;
}
private Statement getStatement()
throws SQLException, ClassNotFoundException {
if (null == statement) statement = getConnection().createStatement();
return statement;
}
/** 釋放所有資源 */
public void destroyed() {
try {
if (null != connection) { connection.close(); connection = null; }
if (null != statement) { statement.close(); statement = null; }
if (null != resultSet) { resultSet.close(); resultSet = null; }
} catch (SQLException e) {
logger.error("Sqlite 資料庫關閉時異常", e);
}
}
}
所有查詢/更新方法都放在 try-finally 中,確保不論成功與否都會收尾。
public interface ResultSetExtractor<T> {
public abstract T extractData(ResultSet rs);
}
public interface RowMapper<T> {
public abstract T mapRow(ResultSet rs, int index) throws SQLException;
}
public class SqliteTest {
@Test
public void testHelper() {
try {
SqliteHelper h = new SqliteHelper("testHelper.db");
h.executeUpdate("drop table if exists test;");
h.executeUpdate("create table test(name varchar(20));");
h.executeUpdate("insert into test values('sqliteHelper test');");
List<String> sList = h.executeQuery("select name from test",
new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int index)
throws SQLException {
return rs.getString("name");
}
});
System.out.println(sList.get(0));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
執行後輸出:
sqliteHelper test
這個封裝的優點是擴充容易——需要聚合值時改用 ResultSetExtractor,需要列表時用 RowMapper;缺點是每次操作後都關閉連線,若應用需要頻繁存取,可再包一層連線池或改用 PreparedStatement 搭配參數綁定,避免 SQL 拼接帶來的安全風險。