SQLite——Java使用SQLite初体验

前言

SQLite相比大多数数据库而言,具有免安装等优势,广泛应用于测试Android等领域。

通过一个.db文件就能实现数据库连接DDL操作语句DML命令。

依赖版本

测试项目采取Maven开发模式,其中主要依赖如下:

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

SQLite 操作工具类(自写)

自己定义了一个连接操作的工具类,工具类代码如下所示:

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * sqlite帮助类,直接创建该类示例,并调用相应的借口即可对sqlite数据库进行操作
 *
 * 本类基于 sqlite jdbc v56
 *
 * @author
 */
public class SqliteHelper {

    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    private String dbFilePath;

    /**
     * 构造函数
     * @param dbFilePath sqlite db 文件路径
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public SqliteHelper(String dbFilePath) throws ClassNotFoundException, SQLException {
        this.dbFilePath = dbFilePath;
        connection = getConnection(dbFilePath);
    }

    /**
     * 获取数据库连接
     * @param dbFilePath db文件路径
     * @return 数据库连接
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public Connection getConnection(String dbFilePath) throws ClassNotFoundException, SQLException {
        Connection conn = null;
        // 1、加载驱动
        Class.forName("org.sqlite.JDBC");
        // 2、建立连接
        // 注意:此处有巨坑,如果后面的 dbFilePath 路径太深或者名称太长,则建立连接会失败
        conn = DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);
        return conn;
    }

    /**
     * 执行sql查询
     * @param sql sql select 语句
     * @param rse 结果集处理类对象
     * @return 查询结果
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public <T> T executeQuery(String sql, ResultSetExtractor<T> rse) throws SQLException, ClassNotFoundException {
        try {
            resultSet = getStatement().executeQuery(sql);
            T rs = rse.extractData(resultSet);
            return rs;
        } finally {
            destroyed();
        }
    }

    /**
     * 执行select查询,返回结果列表
     *
     * @param sql sql select 语句
     * @param rm 结果集的行数据处理类对象
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    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;
    }

    /**
     * 执行数据库更新sql语句
     * @param sql
     * @return 更新行数
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public int executeUpdate(String sql) throws SQLException, ClassNotFoundException {
        try {
            int c = getStatement().executeUpdate(sql);
            return c;
        } finally {
            destroyed();
        }

    }

    /**
     * 执行多个sql更新语句
     * @param sqls
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public void executeUpdate(String...sqls) throws SQLException, ClassNotFoundException {
        try {
            for (String sql : sqls) {
                getStatement().executeUpdate(sql);
            }
        } finally {
            destroyed();
        }
    }

    /**
     * 执行数据库更新 sql List
     * @param sqls sql列表
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    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) {
            System.out.println("Sqlite数据库关闭时异常 "+ e);
        }
    }

    /**
     * 是否自动提交事务
     */
    public void setAutoCommit(Boolean status) throws SQLException {
        connection.setAutoCommit(status);
    }
}

其他相关类

import java.sql.ResultSet;
import java.sql.SQLException;

public interface RowMapper<T> {
    public abstract T mapRow(ResultSet rs, int index) throws SQLException;
}
import java.sql.ResultSet;
import java.sql.SQLException;

public interface ResultSetExtractor<T> {

    public abstract T extractData(ResultSet rs) throws SQLException;

}

建立连接

SQLite只需要关联一个.db文件,就能实现数据库的连接操作。

即使这个.db文件只是一个db文件格式的空文件

测试项目结构如下:
在这里插入图片描述
为了避免文件不存在,导致出现文件找不到的异常,需要优先判断文件的存在性,完整代码如下所示:

// db 文件存放路径地址
static String dbPath = System.getProperty("user.dir")+ File.separator+"db"+File.separator;
// 1、创建sqlite连接
String dbFilePath = dbPath + "sqlite-test.db";
// 需要判断文件是否存在,不存在则优先创建 .db 文件
File dbFile = new File(dbFilePath);
// 如果父路径不存在,则先创建父路径
if(!dbFile.getParentFile().exists()){
    dbFile.getParentFile().mkdirs();
}
// 如果文件不存在,则创建文件
if(!dbFile.exists()){
    dbFile.createNewFile();
}

// 建立连接
SqliteHelper sqliteHelper = new SqliteHelper(dbFilePath);

其中,建立数据库连接的核心代码如下所示:

/**
 * 构造函数
 * @param dbFilePath sqlite db 文件路径
 * @throws ClassNotFoundException
 * @throws SQLException
 */
public SqliteHelper(String dbFilePath) throws ClassNotFoundException, SQLException {
    this.dbFilePath = dbFilePath;
    connection = getConnection(dbFilePath);
}

/**
 * 获取数据库连接
 * @param dbFilePath db文件路径
 * @return 数据库连接
 * @throws ClassNotFoundException
 * @throws SQLException
 */
public Connection getConnection(String dbFilePath) throws ClassNotFoundException, SQLException {
    Connection conn = null;
    // 1、加载驱动
    Class.forName("org.sqlite.JDBC");
    // 2、建立连接
    // 注意:此处有巨坑,如果后面的 dbFilePath 路径太深或者名称太长,则建立连接会失败
    conn = DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);
    return conn;
}

与JDBC类似,也是先加载连接驱动,再通过驱动管理器 DriverManager构建连接通道。

但这里相比其他数据库而言,有一定的区别:

  • 1、getConnection(@NotNull String url) 中的 url 是 .db文件的全路径
  • 2、路径地址不能太深!
  • 3、文件名不能太长。

当代码执行后,项目的db文件夹中则会出现一个sqlite-test.db的文件。

但这个文件目前仅仅是一个.db后缀的空文件

建表DDL

建立连接后,进行数据表的建立。实现方式如下所示:

// 此时只是针对 sqlite-test.db 这个文件进行了连接操作,但这个文件才创建,其中无任何信息
// 2、建表 DDL
String createUser = "create table if not exists user(id integer primary key autoincrement,username varchar(20),password varchar(20))";
// 执行sql
sqliteHelper.executeUpdate(createUser);

该代码执行后,会在sqlite-test.db文件中创建一个user表,如下所示:
在这里插入图片描述
但其中并无数据信息。

插入数据、查询数据、删除数据 DML

// 3、插入数据
String insertUserData = "insert into user(username,password) values ('xiangjiao','123456')";
sqliteHelper.executeUpdate(insertUserData);

// 4、查询语句
String selectUserData = "select * from user";
//        List<Object> query = sqliteHelper.executeQuery(selectUserData, new RowMapper<Object>() {
//            @Override
//            public Object mapRow(ResultSet rs, int index) throws SQLException {
//                Map<String, Object> resultMap = new HashMap<>();
//                resultMap.put("id", rs.getString("id"));
//                resultMap.put("username", rs.getString("username"));
//                resultMap.put("password", rs.getString("password"));
//                return resultMap;
//            }
//        });
// JDK 1.8 可以使用下列方式
List<Object> query = sqliteHelper.executeQuery(selectUserData, (rs,index)->{
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("id", rs.getString("id"));
    resultMap.put("username", rs.getString("username"));
    resultMap.put("password", rs.getString("password"));
    return resultMap;
});

query.forEach(e->{
    System.out.println(e);
});

System.out.println("================");


// 5、删除信息
String deleteSql = "delete from user where id = 1";
sqliteHelper.executeUpdate(deleteSql);
// 再查询
String selectUserData2 = "select * from user";
// JDK 1.8 可以使用下列方式
List<Object> query2 = sqliteHelper.executeQuery(selectUserData2, (rs,index)->{
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("id", rs.getString("id"));
    resultMap.put("username", rs.getString("username"));
    resultMap.put("password", rs.getString("password"));
    return resultMap;
});
query2.forEach(e-> System.out.println(e));

删除数据表 DDL

// 6、删除整张表
String dropTable = "drop table user";
sqliteHelper.executeUpdate(dropTable);

查看db文件工具

  • SQLite Expert Personal 5
  • dbeaver
  • navicat

版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_38322527/article/details/125717093