關於Java 項目封裝sqlite連接池操作持久化數據的方法

Sqlite

sqlite是C實現的一個開源SQL引擎,其api提供sql語法支持,通過sql解析後對存儲層的磁盤文件進行操作,完整配置的sqlite庫小於400kb,多用於移動端應用,小型項目中。

對Sqlite有興趣的可以瞭解下其體系結構

在這裡插入圖片描述

之前自研SQL解析器的時候便是借鑒瞭SQLcompiler的源碼,這裡不展開介紹

封裝Java的Sqlite連接池

首先maven項目引入依賴sqlite-jdbc,其主要是java版的sqliteapi,關於Sqlite api的操作,大傢可以看菜鳥教程

<dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.30.1</version>
    </dependency>

同時引入spring jdbc方便解析數據

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.12</version>
        </dependency>

先編寫測試用例

import org.junit.Test;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class TestSqliteHelper {

    @Test
    public void test() throws SQLException, ClassNotFoundException {
        SqliteHelper sqliteHelper = SqliteHelper.GetSqliteHelper("test.db");

        String sql = "CREATE TABLE COMPANY " +
                "(ID INT PRIMARY KEY     NOT NULL," +
                " NAME           TEXT    NOT NULL, " +
                " AGE            INT     NOT NULL, " +
                " ADDRESS        CHAR(50), " +
                " SALARY         REAL)";
        
        sqliteHelper.ExecuteUpdate(sql);

        sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
                "VALUES (1, 'Paul', 32, 'California', 20000.00 );";

        sqliteHelper.ExecuteUpdate(sql);

        sql = "SELECT * FROM COMPANY;";

        List<String> datas = new LinkedList<>();
        datas = sqliteHelper.ExecuteQuery(sql, new RowMapper<String>() {
                    @Override
                    public String mapRow(ResultSet rs, int index)
                            throws SQLException {
                        return rs.getString("NAME");

                    }
                }
        );

        sqliteHelper.PutSqliteHelper();
    }
}


再根據TDD實現ExecuteUpdate\GetSqliteHelper、ExecuteQuery、PutSqliteHelper等方法

import org.springframework.jdbc.core.RowMapper;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class SqliteHelper {

    /**
     * 磁盤文件名 即db
     */
    private String path = null;

    /**
     * 操作鏈接
     */
    private Connection connection = null;

    /**
     * 語法執行層
     */
    private Statement statement = null;

    /**
     * 構建一次鏈接
     *
     * @param path
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    SqliteHelper(String path) throws SQLException, ClassNotFoundException {
        this.path = path;
        this.connection = this.getConnect(path);
    }

    /**
     * 讀寫鎖,也可以使用ConcurrentHashMap
     */
    static ReentrantLock hashMapLock = new ReentrantLock();

    /**
     * Sqlite的連接池
     */
    static HashMap<String, List<SqliteHelper>> sqlitePool = new HashMap<>();

    /**
     * sqlite對磁盤文件的操作是在一次連接上執行
     *
     * @param path sqlite數據存儲的磁盤文件
     * @return
     */
    public static SqliteHelper GetSqliteHelper(String path) throws SQLException, ClassNotFoundException {
        hashMapLock.lock();
        List<SqliteHelper> sqliteHelpers = sqlitePool.get(path);
        if (sqliteHelpers == null) {
            sqliteHelpers = new LinkedList<>();
            sqlitePool.put(path, sqliteHelpers);
        }
        SqliteHelper sqliteHelper = new SqliteHelper(path);
        sqliteHelpers.add(sqliteHelper);
        return sqliteHelper;
    }

    public void PutSqliteHelper() throws SQLException {
        hashMapLock.lock();
        List<SqliteHelper> sqliteHelpers = sqlitePool.get(this.path);
        if (sqliteHelpers == null) {
            sqliteHelpers = new LinkedList<>();
            sqlitePool.put(path, sqliteHelpers);
        }
        if(sqliteHelpers.size() > 2){
            releaseConn();
        }else{
            sqliteHelpers.add(this);
        }
    }
    /**
     * 獲取Sqlite操作鏈接
     *
     * @param path sqlite數據表,為磁盤文件名
     * @return
     */
    private Connection getConnect(String path) throws ClassNotFoundException, SQLException {
        Connection c = null;
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:" + path);
        return c;
    }

    /**
     * @param sql 執行的sqlite 語句
     * @param row
     * @param <T> 映射的模板
     * @return
     */
    public <T> List<T> ExecuteQuery(String sql, RowMapper<T> row) throws SQLException {
        try {
            List<T> datas = new ArrayList<>();
            ResultSet resultSet = getStmt().executeQuery(sql);
            while (resultSet.next()) {
                datas.add(row.mapRow(resultSet, resultSet.getRow()));
            }
            resultSet.close();
            return datas;
        } finally {
            releaseConn();
        }
    }

    public void ExecuteUpdate(String sql) throws SQLException {
        getStmt().executeUpdate(sql);
    }

    private Statement getStmt() throws SQLException {
        if (this.statement == null) {
            this.statement = this.connection.createStatement();
        }
        return this.statement;
    }


    private void releaseConn() throws SQLException {
        if (this.connection != null) {
            this.connection.close();
            this.connection = null;
        }

        if (this.statement != null) {
            this.statement.close();
            this.statement = null;
        }
    }

}

到此這篇關於Java 項目封裝sqlite連接池操作持久化數據的文章就介紹到這瞭,更多相關java sqlite連接池操作內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: