C# 程序中使用 SQLite 数据库

差不多在 3 年前我就关注过 SQLite,也整理了一篇 SQLite 的介绍:开源嵌入式数据库 SQLite 简介, 还在我的一个查手机归属地软件中使用了 SQLite 数据库,http://unmi.cc/csharp-use-sqlite-db/

现在又要用到 C# 了,所以决意了解下 C# 中如何使用 SQLite,之所以选择 SQLite 作为自己的文件型数据,主要是看中它的非常小型单文件嵌入型,更支持多进程访问。

SQLite 官方网站:http://www.sqlite.org,你可以在那里下载到一个 sqlite3.exe,用命令行模式来管理你的数据库文件。或用其他比较好的管理工具:sqliteman(也支持 UTF-8) 、sqlitebrowser 和 SQLite Administrator。我比较喜欢 sqlitebrowser,但更推荐可设置字符集的 SQLite Expert(可下载到免费的个人版)。

既然是嵌入式数据库,只要些动态库就行,如 dll 原生库,jar 包或其他语言的组件库形式,.NET 中也不例如,要用到 System.Data.SQLite,下载安装后在安装目录中你有你所需的各种文件,使用 SQLite 只要在你的 .NET 应用引入 System.Data.SQLite.dll,如果要支持 LINQ,还要引入 System.Data.SQLite.Linq.dll。它支持到 ADO.NET 3.5,被 NHibernate 支持,并能集成在 VS2005/2008,且提供 64 位版,WinCE 版的动态库。SQLite.NET 也带了个帮助文档。

下面来直接看个例子,基本是借用了 C#使用SQLite数据库(asp.net/winform) 中的例子。
 1using System;
 2using System.Data;
 3using System.Data.SQLite;
 4
 5//C# 使用 SQLite 数据测试程序
 6public class Program
 7{
 8    public static void Main(string[] args)
 9    {
10        using (SQLiteConnection con = new SQLiteConnection("Data Source=c:\\test.db3;Pooling=true;FailIfMissing=false"))
11        {
12            //打开数据库文件 c:\\test.db3,不存在则创建
13            con.Open();
14
15            using (SQLiteCommand cmd = new SQLiteCommand())
16            {
17                cmd.Connection = con;
18
19                //检查是否存在表 test,不存在则创建
20                Boolean testTableExists = false;
21                cmd.CommandText = "SELECT * FROM sqlite_master WHERE type='table' and name='test'";
22                using(SQLiteDataReader dr = cmd.ExecuteReader())
23                {
24                    if (dr.Read())
25                    {
26                        testTableExists = true;
27                    }
28                }
29                if (!testTableExists)
30                {
31                    cmd.CommandText = "CREATE TABLE [test] (id int, name nvarchar(20))";
32                    cmd.ExecuteNonQuery();
33                }
34
35                //清空 test 表
36                cmd.CommandText = "DELETE FROM [test]";
37                cmd.ExecuteNonQuery();
38
39                //插入测试数据
40                for (int i = 1; i <= 5; i++)
41                {
42                    cmd.CommandText = string.Format("INSERT INTO [test] VALUES ({0}, '中文测试')", i);
43                    cmd.ExecuteNonQuery();
44                }
45
46                //读取数据
47                cmd.CommandText = "SELECT * FROM [test]";
48                using (SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
49                {
50                    while (dr.Read())
51                    {
52                        Console.WriteLine("第{0} 条:{1}", dr.GetValue(0), dr.GetString(1));
53                    }
54                }
55            }
56        }
57
58        Console.WriteLine("Press any key to continue...");
59        Console.ReadKey();
60    }
61}

运行之后,你会发现,中文可以插入,并且显示出来也没问题,但是用一般的 SQLite 管理工具看到的却是乱码。同样,在其他客户端中输入的中文让上面程序读出来也是乱码。幸运的是还是找到一种客户端工具 SQLite Expert(可下载到免费的个人版), 看到的结果是中文,这是因为 System.Data.SQLite 默认使用的是 UTF-8 字符集,而 SQLite Expert 有字符集的选择可设置的。其他的客户端默认的字符集都是 ANSI,也就是 ISO8859-1 吧。

其他相关内容:连接字符串的参数配置:

在安装后的 SQLite.NET Help 帮助文档中可以查到详细的连接参数说明. 查 ConnectionString Property,或看链接:Connection String:

ParameterValuesRequiredDefault
Version3N3
Data Source{filename}Y 
Version3N3
UseUTF16EncodingTrue
False
NFalse
DateTimeFormatTicks - Use DateTime.Ticks
ISO8601 - Use ISO8601 DateTime format
NISO8601
BinaryGUIDYes/On/1 - Store GUID columns in binary form
No/Off/0 - Store GUID columns as text
NOn
Cache Size{size in bytes}N2000
SynchronousNormal - Normal file flushing behavior
Full - Full flushing after all writes
Off - Underlying OS flushes I/O's
NNormal
Page Size{size in bytes}N1024
Password{password}N 
EnlistY - Automatically enlist in distributed transactions
N - No automatic enlistment
NY
PoolingTrue - Use connection pooling
False - Do not use connection pooling
NFalse
FailIfMissingTrue - Don't create the database if it does not exist, throw an error instead
False - Automatically create the database if it does not exist
NFalse
Max Page Count{size in pages} - Limits the maximum number of pages (limits the size) of the databaseN0
Legacy FormatTrue - Use the more compatible legacy 3.x database format
False - Use the newer 3.3x database format which compresses numbers more effectively

留意其中几个参数,或许对你有用。比如 System.Data.SQLite 单方面支持密码保护,但其他的 SQLite 客户端无法读取这样的文件。

参考:1. C#使用SQLite数据库(asp.net/winform)
        2. SQLite——只要3分钟,你就可以在.NET上创建和运行它
        3. SQLite GUI 客户端列表
        4. (学)关于SQLite乱码问题解决办法

永久链接 https://yanbin.blog/csharp-use-sqlite-db/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。