SQLite简单使用(C# ADO.net)

从SQLite官网下载获取System.Data.SQLite库并安装。新建C# Console Application项目并添加对System.Data.SQLite.dll的引用。

SQLite简单使用(C ADO.net) - 秒大刀 - 秒大刀的城堡 

然后 添加/现有项/SQLite.Interop.dll 添加为链接

SQLite简单使用(C ADO.net) - 秒大刀 - 秒大刀的城堡 

将SQLite.Interop.dll 属性/复制到输出目录 改为“如果较新则复制”

SQLite简单使用(C ADO.net) - 秒大刀 - 秒大刀的城堡 

在项目目录新建数据库Content.db3,并运行以下SQL在main库中创建files表:

CREATE TABLE files(

name text primary key not null,

data blob not null

);

SQLite简单使用(C ADO.net) - 秒大刀 - 秒大刀的城堡 

将以下代码加入C#项目即可顺利跑起Demo:

class Program

{

private static readonly System.Data.SQLite.SQLiteCommand commandCount;

private static readonly System.Data.SQLite.SQLiteCommand commandInsert;

 

static Program()

{

commandCount = new System.Data.SQLite.SQLiteCommand();

commandCount.CommandText = "select count(*) from main.files";

 

commandInsert = new System.Data.SQLite.SQLiteCommand();

commandInsert.CommandText = "replace into main.files values(@name, @data)";

}

 

static void Test()

{

using (var conn = new System.Data.SQLite.SQLiteConnection(

"DbLinqProvider=Sqlite;Data Source=http://www.cnblogs.com/Content.db3"))

{

conn.Open();

commandCount.Connection = conn;

commandInsert.Connection = conn;

 

using (var reader = commandCount.ExecuteReader())

{

while (reader.Read())

{

Console.WriteLine(reader.GetValue(0));

}

}

 

commandInsert.Parameters.Add(new System.Data.SQLite.SQLiteParameter(

"name", "2"));

commandInsert.Parameters.Add(new System.Data.SQLite.SQLiteParameter(

"data", new byte[] { 0x00, 0x01, 0x02 }));

int n = commandInsert.ExecuteNonQuery();

Console.WriteLine(n);

 

using (var reader = commandCount.ExecuteReader())

{

while (reader.Read())

{

Console.WriteLine(reader.GetValue(0));

}

}

}

}

 

static void Main(string[] args)

{

Stopwatch watch = new Stopwatch();

watch.Start();

Test();

watch.Stop();

Console.WriteLine(watch.Elapsed);

}

}

SQLite官方提供的System.Data.SQLite库是典型的ADO.net接口访问方式,能和.net框架很好的配合起来,简单有效。

原文地址:https://www.cnblogs.com/lvfeilong/p/SQLite1.html