您的位置:首页 > 数据库

C# 程序中使用 SQLite 数据库

2012-02-04 18:48 281 查看

C# 程序中使用 SQLite 数据库

2010-05-06 — Unmi

差不多在 3 年前我就关注过 SQLite,也整理了一篇 SQLite 的介绍:开源嵌入式数据库 SQLite 简介, 还在我的一个查手机归属地软件中使用了 SQLite 数据库,http://www.blogjava.net/Unmi/archive/2007/12/15/126225.html

现在又要用到 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) 中的例子。

运行之后,你会发现,中文可以插入,并且显示出来也没问题,但是用一般的 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乱码问题解决办法

本文链接 http://unmi.cc/csharp-use-sqlite-db, 来自
隔叶黄莺 Unmi Blog
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息