今天公司要求将MySql数据库中的指定表导出为Sqlite的DB文件,在此记录一下关键的地方
引入maven依赖
引入sqlite JDBC依赖
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.23.1</version>
</dependency>
生成DB文件的关键代码
最关键的代码是connection = DriverManager.getConnection(url, username, password);建立一个数据库名DB的连接,如果不存在就在当前目录下创建。
public static void setConnection() {
try {
// 声明驱动类型
Class.forName("org.sqlite.JDBC");
// 设置sqlite db文件存放基本目录
String path = DBUtil.class.getClassLoader().getResource("").getPath();
// 设置 sqlite文件路径,等同于mysql连接地址(jdbc:mysql://127.0.0.1:3306/test)
String url = "jdbc:sqlite:" + path + "data.db";
// 获取连接 关键代码
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
} catch (Exception e) {
throw new RuntimeException("建立Sqlite连接失败");
}