SQLite Helper(C#)

介绍

         SQLite 是一个开源的,可嵌入的,跨平台的(Window,IOS,Android,Linux)数据库引擎,它在客户端工作的时候不需要安装和配置。

         我写了一个SQLiteHelper类,它可以用于在C#中使用SQLite。

首要条件

         这个SQLiteHelper.cs类是建立在System.Data.SQLite.DLL。这个引用必须添加到你的项目工程当中。

         下载地址:https://system.data.sqlite.org

方法列表

1.      GetTableStatus

2.      GetTableList

3.      GetColumnStatus

4.      CreateTable

5.      UpdateTableStructure

6.      BeginTransaction,Commit,Rollback

7.      Select

8.      Execute

9.      ExecuteScalar

10.  Escape

11.  Insert

12.  Update

13.  LastInsertRowId

14.  RenameTable

15.  CopyAllData

16.  DropTable

17.  ShowDatabase

18.  AttackDatabase,DetachDatabase

 

开始

         在类的最开始位置添加下面的引用:

        using System.Data.SQLite;

 

         在使用SQLiteHelper之前需要初始化SQLiteConnection和SQLiteCommand.例如:

using (SQLiteConnection conn = new SQLiteConnection("data source=C:\\data"))

{

    using (SQLiteCommand cmd =new SQLiteCommand())

    {

       cmd.Connection = conn;

       conn.Open();

       SQLiteHelper sh = new SQLiteHelper(cmd);

        // do something...

       conn.Close();

    }

}

1.      GetTableStatus

从数据库中获取所有的表信息。

DataTable dt = sh.GetTableStatus();

结果示例:

type

name

tbl_name

rootpage

sql

table

sqlite_sequence

sqlite_sequence

3

CREATE TABLE sqlite_sequence(name,seq)

table

person2

person2

5

CREATE TABLE "person2"(
id integer primary key autoincrement,
name text,
tel text,
email text,
job text,
remarks text)

table

player

player

4

CREATE TABLE `player`(
id integer primary key autoincrement,
lvl integer,
weaponid integer,
teamid integer,
location text,
team_name text,
remarks text)

table

product

product

6

CREATE TABLE "product"(
id integer primary key autoincrement,
name text,
qty integer)

2.      GetTableList

从数据库中获取表的列表。

DataTable dt = sh.GetTableList()

3.      GetColumnStatus

在指定表中获取这个列的所有信息。

// Get column's information from table "person"
DataTable dt = sh.GetColumnStatus("person");

结果示例:

cid

name

type

notnull

dflt_value

pk

0

id

integer

0

1

1

lvl

integer

0

0

2

weaponid

integer

0

0

3

teamid

integer

0

0

4

location

text

0

0

5

team_name

text

0

0

6

remarks

text

0

0

4.      CreateTable

创建表。

例如Person表的结构如下:

Column Name

Data Type

Primary Key

Auto Increment

Not Null

Default Value

id

int

true

true

name

text

membershipid

int

level

decimal

5.5

SQLiteTable tb = new SQLiteTable("person");
 
tb.Columns.Add(new SQLiteColumn("id", true));
tb.Columns.Add(new SQLiteColumn("name"));
tb.Columns.Add(new SQLiteColumn("membershipid", ColType.Integer));
tb.Columns.Add(new SQLiteColumn("level", ColType.Decimal, false, false, "5.5"));
 
sh.CreateTable(tb);

5.      UpdateTableStructure

正如名字所说,它是用于更新表的结构。或许你可以添加新的列,或者是删除某些列

这个方法可以帮助你修改表结构。

代码的执行步骤:

*假设这个旧表的名字是:Person

*用类创建一个新定义的临时表(名字是:Person_temp)

*从Person中赋值所有的行到Person_temp

*删除Person表

*重命名Person_temp,将其变为Person

代码示例:

SQLiteTable tb = new SQLiteTable();
tb.Columns.Add(new SQLiteColumn("id", true));
tb.Columns.Add(new SQLiteColumn("name"));
tb.Columns.Add(new SQLiteColumn("sku"));
tb.Columns.Add(new SQLiteColumn("code"));
tb.Columns.Add(new SQLiteColumn("category"));
tb.Columns.Add(new SQLiteColumn("remarks"));
 
sh.UpdateTableStructure("person", tb);

6.      BeginTransaction,Commit,RollBack

什么是事务?

在默认情况下,每一个SQL查询在SQLite数据库引擎事务中执行。数据库会自动的开启

事务并且在最后提交事务。提交事务就是让你对数据库的操作有效。

         如果我们发送了3条Sql 语句(INSERT,UPDATE,DELETE,etc。。。),那么就会产生3个事务。根据SQLite的官方文档的FAQ:

         “...一个事务通常需要两个完全转动的磁盘,这个磁盘拥有7200的转速,它一秒可以执行最多60个事务。”

         这就意味着,7200RPM的硬盘,我们在一秒钟内最多能够执行60次的Insert或者Update或者Delete操作。

         但是如果我们认为的加入BEGIN TRANSACTION,所有的查询语句将会被算作是一个事务,这样的话SQLite在一个事务当中可以执行很多的操作。有些人会说他能够在一秒钟执行1千万次的操作在stackoverflow.com中,但是这也取决于你使用的硬盘的速度。

代码示例:

sh.BeginTransaction();
 
try
{
    // INSERT.....
    // INSERT.....
    // UPDATE....
    // ... skip for another 50,000 queries....
    // DELETE....
    // UPDATE...
    // INSERT.....
 
    sh.Commit();
}
catch
{
    sh.Rollback();
}

ROLLBACK,在上面的实例中可以看出,它就是取消事务的意思,所有送往SQLite数据库且在指定事务内的查询操作将会失效。

7.      Select

返回DataTable样式的查询结果。

·        Select(stringsql)

·        Select(stringsql, Dictionary<string, object> dicParameters = null)

·        Select(stringsql, IEnumerable<SQLiteParameter> parameters = null)

Example 1:

DataTable dt = sh.Select("select * fromperson order by id;");

Example 2(有参数的情况下):

var dic = new Dictionarystring, object();

dic["@aaa"] = 1;

dic["@bbb"] = 1;

DataTable dt = sh.Select("select * frommember where membershipid = @aaa and locationid = @bbb;", dic);

Example 3(有参数的情况下):

DataTable dt = sh.Select("select * frommember where membershipid = @aaa and locationid = @bbb;",

    new SQLiteParameter[] {

        new SQLiteParameter("@aaa", 1),

        new SQLiteParameter("@bbb", 1)

    });

8.      Execute

执行单个SQL查询

·        Execute(stringsql)

·        Execute(stringsql, Dictionary<string, object> dicParameters = null)

·        Execute(stringsql, IEnumerable<SQLiteParameter> parameters = null)

Example:

sh.Execute("insert into person(name)values('hello');");

9.      ExecuteScalar

返回特定数据类型的第一行第一列的结果。

·        ExecuteScalar(stringsql)

·        ExecuteScalar(stringsql, Dictionary<string, object> dicParameters = null)

·        ExecuteScalar(stringsql, IEnumerable<SQLiteParameter> parameters = null)

·        ExecuteScalar<datatype>(stringsql)

·        ExecuteScalar<datatype>(stringsql, Dictionary<string, object> dicParameters = null)

·        ExecuteScalar<datatype>(stringsql, IEnumerable<SQLiteParameter> parameters = null)

Example:

string a = sh.ExecuteScalar<string>("select 'Hello!';");

 

int b = sh.ExecuteScalar<int>("select 1000;");

 

decimal c = sh.ExecuteScalar<decimal>("select 4.4;");

 

DateTime d = sh.ExecuteScalar<DateTime>("selectdate('now');");

 

byte[] e = sh.ExecuteScalar<byte[]>("select randomblob(16);");

10.  Escape

规范文本值的顺序,避免SQL注入或者是构成无效的SQL语法。

sh.Execute("insert into person(name) values('" + Escape(input) + "');");

11.  Insert

插入一行新的数据。所有添加的数据将会已参数的形式在代码后面出现,在这里也支持

blob数据类型的值。

var dic = new Dictionary<string, object>();

dic["name"] = "John";

dic["membershipid"] = 1;

dic["level"] = 6.8;

 

sh.Insert("person", dic);

12.  Update

更新一行。所有更新的数据将会以参数的形式出现在代码后面,在这里也支持blob数据

类型的值。

Example 1:单一条件下的更新

var dicData = new Dictionary<string, object>();

dicData["name"] = "no name";

dicData["membershipid"] = 0;

dicData["level"] = 5.5;

 

sh.Update("person", dicData, "id", 1);

Example 2:多条件下的更新:

var dicData = new Dictionary<string, object>();
dicData["name"] = "no name";
dicData["status"] = 0;
dicData["money"] = 100;
dicData["dateregister"] = DateTime.MinValue;
 
var dicCondition = new Dictionary<string, object>();
dicCondition["membershipid"] = 1;
dicCondition["level"] = 5.5;
dicCondition["teamid"] = 1;
 
sh.Update("person", dicData, dicCondition);

13.  LastInsertRowId

获取最后生成的id(自增长类型)。

sh.Insert("person", dicData);
long id = sh.LastInsertRowId();

14.  RenameTable

重命名表。

sh.RenameTable("person", "person_backup");

15.  CopyAllData

从一个表中复制所有数据到另一个表。

sh.CopyAllData("person", "person_new");

在复制前,SQLiteHelper将会查看这两个表的表结构是否相同,只有表结构相同的才会

进行复制操作。

16.  DropTable

删除表。

sh.DropTable("person");

17.  ShowDatabase

显示连接的数据库。

DataTable dt = sh.ShowDatabase();

18.  AttachDatabase,DetachDatabase

连接数据库或者释放数据库

sh.AttachDatabase("C:\\data2013.sq3", "lastyeardb");
sb.DetachDatabase("lastyeardb");

 

 


Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐