Sqlite implementation

This commit is contained in:
ChessNineeee committed 2021-04-02 15:43:28 +08:00
1 parent 036c4d3dc9
commit 402267fa57
2 files changed
+78 -5

No files matched your search

+9
View File
@@ -94,6 +94,15 @@
<version>3.0.8</version>
</dependency>
<!-- Sqlite Driver-->
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.28.0</version>
</dependency>
</dependencies>
</project>
@@ -1,5 +1,8 @@
package minsecurity.identity.persist.sqlite;
import java.io.File;
import java.sql.*;
/*
* @Author: zhengqi wu
* @Description: Sqlite封装
@@ -13,6 +16,20 @@ public class Sqlite {
private String passwd = "2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99"; // 初始数据库密码
private String db_file = "identity.db"; // 数据库文件名
private String db_path = "";
private String table_create = "CREATE TABLE IF NOT EXISTS \"identityinfo\" (\n" +
"\t\"name\"\tvarchar(255) NOT NULL,\n" +
"\t\"pubkey\"\tvarchar(255),\n" +
"\t\"prikey\"\tvarchar(255),\n" +
"\t\"pubkey_algo\"\tint,\n" +
"\t\"signature_algo\"int,\n" +
"\t\"pass\"\tvarchar(255),\n" +
"\t\"cert\"\tTEXT,\n" +
"\t\"is_default\"\tint DEFAULT 0,\n" +
"\t\"prikey_raw_byte\" varchar(255),\n" +
"\tPRIMARY KEY(\"name\")\n" +
");";
private Sqlite(){
}
@@ -37,18 +54,65 @@ public class Sqlite {
passwd = pass;
}
public void open(String filePath){
/**
* 进行数据库文件的连接测试,如果表不存在则新建
* 数据库文件默认写入地址为~/.min/identity/identity.db
* @throws Exception
*/
public void openDefault() throws Exception {
Connection c = null;
Statement stmt = null;
try{
String homePath = SqliteUtil.home();
homePath += "/min/identity";
String dbPath = homePath;
if (!SqliteUtil.pathExists(dbPath)){
new File(dbPath).mkdirs();
}
String real_db_file = dbPath + db_file;
c = DriverManager.getConnection("jdbc:sqlite:" + real_db_file);
stmt = c.createStatement();
stmt.executeUpdate(table_create);
stmt.close();
c.close();
}catch (Exception ex){
if (c != null)
c.close();
throw ex;
}
}
//自定义文件地址,注意要用/结尾,比如:/min/identity/
public void open(String filePath) throws Exception {
Connection c = null;
Statement stmt = null;
try{
boolean db_exists = SqliteUtil.pathExists(filePath);
if (!db_exists){
new File(filePath).mkdirs();
}
String real_db_file = filePath + db_file;
c = DriverManager.getConnection("jdbc:sqlite:" + real_db_file);
stmt = c.createStatement();
stmt.executeUpdate(table_create);
stmt.close();
c.close();
}catch (Exception ex){
// TODO 出错时关闭数据库
// DONE 出错时关闭数据库
if (c != null)
c.close();
throw ex;
}
}
public Connection getConn() throws SQLException {
Connection c = null;
try{
String real_db_file = db_path + db_file;
c = DriverManager.getConnection("jdbc:sqlite:" + real_db_file);
// TODO 设置数据库最大连接数
return c;
}catch (Exception ex){
throw ex;
}
}
}