.net core加載加密的sqlite文件失敗解決方案
在項目開發過程中,遇到使用sqlite的場景。在加載加密的sqlite時,連接sqlite時報錯,,先用百度查詢了下資料,尚未找到對應解決方法,故接着在stackoverflow上查找,找到了解決思路,並已解決問題。
1.開發時所用到的相關內容
1.1相關項目組件
組件名稱 | 版本 |
---|---|
Microsoft.NETCore.App | 2.1.0 |
sqlSugarCore | 5.0.0.9 |
1.2 sqlite加密軟件
軟件名稱 | 版本 |
---|---|
SQLiteStudio | 3.1.1 |
2.解決過程
2.1 遇錯過程
剛開始用的時候是直接用SQLiteStudio直接創建了SQLCipher加密的sqlite文件,用sqlsugar進行DB連接時候程序報錯。報錯提示如下:
file is encrypted or is not a database
2.2 第一種解決方案——System.Data.Sqlite
2.2.1 使用System.Data.Sqlite
在sqlite連接的時候,棄用sqlsugar,轉而采用System.Data.Sqlite中的sqliteconnection來連接,這個需要自行從nuget中下載,當前采用是System.Data.Sqlite的最新版本1.0.112,且需要將原先加密方式進行改變,不然仍會報上述的錯誤提示,數據類型要改為System.Data.SQLite,輸入文件名,密碼后重新創建DB文件。
2.2.2 相關Demo代碼
測試的SQLCipher.db3中已存有user表,表中僅有一個varchar(32)的Name字段,數據僅有一條為sqlcipher。以下是測試相關代碼
using System;
using System.Data;
using System.Data.SQLite;
SQLiteConnection clinet = new SQLiteConnection($"Data Source={path3}");
string key = "123456";
clinet.Open();
SQLiteCommand command = clinet.CreateCommand();
command.CommandText = "PRAGMA key = " + key;
command.ExecuteNonQuery();
command.CommandText = "select name from user";
DataTable dt = new DataTable();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
adapter.Fill(dt);
var result = dt.Rows[0][0];
clinet.Close();
運行完畢后,未報錯且成功取到結果。
2.3第二種解決方法—Microsoft.Data.Sqlite
第一種方法實現后,再查找是否有更好的辦法來解決。sqlsugar采用的sqlite連接是用的Microsoft.Data.Sqlite中的連接方式,在使用Microsoft.Data.Sqlite連接加密方法時,目前僅找到對應的連接數據類型為SQLCipher加密的文件的方法
2.3.1引用的包
第一個是引用nuget中的SQLitePCLRaw.bundle_sqlcipher包,我引用的是SQLitePCLRaw.bundle_sqlcipher包的最新版本1.1.14,第二個是Microsoft.Data.Sqlite包,因為sqlsugar中自帶了,故就沒有再次引用,沒有的情況下需要引用Microsoft.Data.Sqlite。
2.3.2 相關Demo代碼
測試的SQLCipher.db3中已存有user表,表中僅有一個varchar(32)的Name字段,數據僅有一條為sqlcipher。以下是測試相關代碼
using System;
using System.Data;
using Microsoft.Data.Sqlite;
string path=@"C:\Users\Administrator\Desktop\SQLCipher.db3";
string key="123456";//密碼
SqliteConnection client=new SqliteConnection($"Data Source={path}");
client.Open();
SqliteCommand command = client.CreateCommand();
command.CommandText = "PRAGMA key = " + key;
command.ExecuteNonQuery();
command.CommandText = "select name from user";
DataTable dt = new DataTable();
SqliteDataAdapter adapter = new SqliteDataAdapter(command);
adapter.Fill(dt);
var result = dt.Rows[0][0];
client.Close();
運行完畢后,未報錯且成功取到結果。
2.4在sqlsugar中使用
需要注意的地方是要在數據庫開啟的時候,先指定密碼,再執行SQL語句,兩者在同一個開啟連接的DB連接中操作。
2.4.1相關Demo代碼
測試的SQLCipher.db3同上,以下是測試相關代碼。
using System;
using SqlSugar;
string path=@"C:\Users\Administrator\Desktop\SQLCipher.db3";
string key="123456";//密碼
ConnectionConfig config = new ConnectionConfig()
{
DbType = SqlSugar.DbType.Sqlite,
ConnectionString = $"Data Source={path}",
IsAutoCloseConnection = false
};
SqlSugarClient client = new SqlSugarClient(config);
client.Open();
client.Ado.ExecuteCommand($"PRAGMA key ={key}}");
var data = client.Queryable<User>().ToList();
client.Close();
運行完畢后,未報錯且結果在data變量中。