之所以选择 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 数据库的例子。
using System;
using System.Data;
using System.Data.SQLite;
//C# 使用 SQLite 数据测试程序
public class Program
{
public static void Main(string[] args)
{
using (SQLiteConnection con = new SQLiteConnection("Data Source=c:\\test.db3;Pooling=true;FailIfMissing=false"))
{
//打开数据库文件 c:\\test.db3,不存在则创建
con.Open();
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.Connection = con;
//检查是否存在表 test,不存在则创建
Boolean testTableExists = false;
cmd.CommandText = "SELECT * FROM sqlite_master WHERE type='table' and name='test'";
using(SQLiteDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
testTableExists = true;
}
}
if (!testTableExists)
{
cmd.CommandText = "CREATE TABLE [test] (id int, name nvarchar(20))";
cmd.ExecuteNonQuery();
}
//清空 test 表
cmd.CommandText = "DELETE FROM [test]";
cmd.ExecuteNonQuery();
//插入测试数据
for (int i = 1; i <= 5; i++)
{
cmd.CommandText = string.Format("INSERT INTO [test] VALUES ({0}, '中文测试')", i);
cmd.ExecuteNonQuery();
}
//读取数据
cmd.CommandText = "SELECT * FROM [test]";
using (SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (dr.Read())
{
Console.WriteLine("第{0} 条:{1}", dr.GetValue(0), dr.GetString(1));
}
}
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
运行之后,你会发现,中文可以插入,并且显示出来也没问题,但是用一般的 SQLite 管理工具看到的却是乱码。同样,在其他客户端中输入的中文让上面程序读出来也是乱码。幸运的是还是找到一种客户端工具 SQLite Expert(可下载到免费的个人版),看到的结果是中文,这是因为 System.Data.SQLite 默认使用的是 UTF-8 字符集,而SQLite Expert 有字符集的选择可设置的。其他的客户端默认的字符集都是 ANSI,也就是 ISO8859-1 吧。
本文来自 隔叶黄莺 Unmi Blog 的 C# 程序中使用 SQLite 数据库。