http://www.codeproject.com/Articles/746191/SQLite-Helper-Csharp

This small class (SQLiteHelper.cs) is built on top of System.Data.SQLite.DLL. A reference of this DLL must be added into your projects.

Download: https://system.data.sqlite.org

List of Simplified Functions

  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. AttachDatabase, DetachDatabase

Getting Start

Add this using statement at the top of your class:

Collapse | Copy Code
  1. using System.Data.SQLite;

SQLiteConnection and SQLiteCommand have to be initialized before using SQLiteHelper:

Example:

Collapse | Copy Code
  1. using (SQLiteConnection conn = new SQLiteConnection("data source=C:\\data"))
  2. {
  3. using (SQLiteCommand cmd = new SQLiteCommand())
  4. {
  5. cmd.Connection = conn;
  6. conn.Open();
  7.  
  8. SQLiteHelper sh = new SQLiteHelper(cmd);
  9.  
  10. // do something...
  11.  
  12. conn.Close();
  13. }
  14. }

1. GetTableStatus

Get all information of tables in the database.

Collapse | Copy Code
  1. DataTable dt = sh.GetTableStatus();

Sample result:

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

Get a list of tables in database.

Collapse | Copy Code
  1. DataTable dt = sh.GetTableList();

3. GetColumnStatus

Get all information of columns in specific table.

Collapse | Copy Code
  1. // Get column's information from table "person"
  2. DataTable dt = sh.GetColumnStatus("person");

Sample Result:

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

Create table.

Example table structure: 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
Collapse | Copy Code
  1. SQLiteTable tb = new SQLiteTable("person");
  2.  
  3. tb.Columns.Add(new SQLiteColumn("id", true));
  4. tb.Columns.Add(new SQLiteColumn("name"));
  5. tb.Columns.Add(new SQLiteColumn("membershipid", ColType.Integer));
  6. tb.Columns.Add(new SQLiteColumn("level", ColType.Decimal, false, false, "5.5"));
  7.  
  8. sh.CreateTable(tb);

5. UpdateTableStructure

As the name said, it is used to update a table's structure. Maybe you have added new columns, or drop/deleted some columns. This method helps you to update it.

The process at code behind:

  • Assume that the old table is named: person
  • The class creates a temporary table (named: person_temp) with your new defined structure.
  • Copy all rows from person to person_temp.
  • Drop/delete table of person.
  • Rename table of person_temp to person

Code example:

Collapse | Copy Code
  1. SQLiteTable tb = new SQLiteTable();
  2. tb.Columns.Add(new SQLiteColumn("id", true));
  3. tb.Columns.Add(new SQLiteColumn("name"));
  4. tb.Columns.Add(new SQLiteColumn("sku"));
  5. tb.Columns.Add(new SQLiteColumn("code"));
  6. tb.Columns.Add(new SQLiteColumn("category"));
  7. tb.Columns.Add(new SQLiteColumn("remarks"));
  8.  
  9. sh.UpdateTableStructure("person", tb);

6. BeginTransaction, Commit, Rollback

What is transaction?

By default, every SQL query that is sent to SQLite database engine happens in a transaction. The engine automatically BEGIN a transaction and COMMIT it at the end. COMMIT is something like "Make it take effect".

If we send 3 SQL queries (INSERT, UPDATE, DELETE, etc...), 3 transactions are taken place. According to [SQLite official documentation - Frequently Asked Questions]:

"...A transaction normally requires two complete rotations of the disk platter, which on a 7200RPM disk drive limits you to about 60 transactions per second..."

Which means, with a 7200RPM hard disk, the best that we can do is 60 INSERTs (or UPDATE, DELETE, etc) per second.

But, If we manually issue a BEGIN TRANSACTION, all the queries will be wrapped in single transaction, then SQLite can execute huge amount of queries per second. Somebody said he can execute 10 million per second at [stackoverflow.com], but this is also depends on the speed of hard disk that you are using.

Code example with SQLiteHelper:

Collapse | Copy Code
  1. sh.BeginTransaction();
  2.  
  3. try
  4. {
  5. // INSERT.....
  6. // INSERT.....
  7. // UPDATE....
  8. // ... skip for another 50,000 queries....
  9. // DELETE....
  10. // UPDATE...
  11. // INSERT.....
  12.  
  13. sh.Commit();
  14. }
  15. catch
  16. {
  17. sh.Rollback();
  18. }

ROLLBACK, in the above example means Cancel Transaction. All queries that have sent to SQLite database within that specific transaction are dismissed.

7. Select

Return the query result in DataTable format.

  • Select(string sql)
  • Select(string sql, Dictionary<string, object> dicParameters = null)
  • Select(string sql, IEnumerable<SQLiteParameter> parameters = null)

Example 1:

Collapse | Copy Code
  1. DataTable dt = sh.Select("select * from person order by id;");

Example 2 (With parameters support):

Collapse | Copy Code
  1. var dic = new Dictionarystring, object();
  2. dic["@aaa"] = 1;
  3. dic["@bbb"] = 1;
  4. DataTable dt = sh.Select("select * from member where membershipid = @aaa and locationid = @bbb;", dic);

Example 3 (With parameters support):

Collapse | Copy Code
  1. DataTable dt = sh.Select("select * from member where membershipid = @aaa and locationid = @bbb;",
  2. new SQLiteParameter[] {
  3. new SQLiteParameter("@aaa", 1),
  4. new SQLiteParameter("@bbb", 1)
  5. });

8. Execute

Execute single SQL query.

  • Execute(string sql)
  • Execute(string sql, Dictionary<string, object> dicParameters = null)
  • Execute(string sql, IEnumerable<SQLiteParameter> parameters = null)

Example:

Collapse | Copy Code
  1. sh.Execute("insert into person(name)values('hello');");

9. ExecuteScalar

Return the result of first row first column in specific data type.

  • ExecuteScalar(string sql)
  • ExecuteScalar(string sql, Dictionary<string, object> dicParameters = null)
  • ExecuteScalar(string sql, IEnumerable<SQLiteParameter> parameters = null)
  • ExecuteScalar<datatype>(string sql)
  • ExecuteScalar<datatype>(string sql, Dictionary<string, object> dicParameters = null)
  • ExecuteScalar<datatype>(string sql, IEnumerable<SQLiteParameter> parameters = null)

Example:

Collapse | Copy Code
  1. string a = sh.ExecuteScalar<string>("select 'Hello!';");
  2.  
  3. int b = sh.ExecuteScalar<int>("select 1000;");
  4.  
  5. decimal c = sh.ExecuteScalar<decimal>("select 4.4;");
  6.  
  7. DateTime d = sh.ExecuteScalar<DateTime>("select date('now');");
  8.  
  9. byte[] e = sh.ExecuteScalar<byte[]>("select randomblob(16);");

10. Escape

Escape string sequence for text value to avoid SQL injection or invalid SQL syntax to be constructed.

Collapse | Copy Code
  1. sh.Execute("insert into person(name) values('" + Escape(input) + "');");

11. Insert

Insert new row of data. All data will be added as parameters at code behind. This support blob (byte[]) value too.

Collapse | Copy Code
  1. var dic = new Dictionary<string, object>();
  2. dic["name"] = "John";
  3. dic["membershipid"] = 1;
  4. dic["level"] = 6.8;
  5.  
  6. sh.Insert("person", dic);

12. Update

Update row. All data will be added as parameters at code behind. This support blob (byte[]) value too.

Example 1: Update with single condition (where id = 1)

Collapse | Copy Code
  1. var dicData = new Dictionary<string, object>();
  2. dicData["name"] = "no name";
  3. dicData["membershipid"] = 0;
  4. dicData["level"] = 5.5;
  5.  
  6. sh.Update("person", dicData, "id", 1);

Example 2: Update with multiple condition (where membership = 1 and level = 5.5 and teamid = 1)

Collapse | Copy Code
  1. var dicData = new Dictionary<string, object>();
  2. dicData["name"] = "no name";
  3. dicData["status"] = 0;
  4. dicData["money"] = 100;
  5. dicData["dateregister"] = DateTime.MinValue;
  6.  
  7. var dicCondition = new Dictionary<string, object>();
  8. dicCondition["membershipid"] = 1;
  9. dicCondition["level"] = 5.5;
  10. dicCondition["teamid"] = 1;
  11.  
  12. sh.Update("person", dicData, dicCondition);

13. LastInsertRowId

Get the last issued id (Auto-Increment)

Collapse | Copy Code
  1. sh.Insert("person", dicData);
  2. long id = sh.LastInsertRowId();

14. RenameTable

Rename a table.

Collapse | Copy Code
  1. sh.RenameTable("person", "person_backup");

15. CopyAllData

Copy all data from one table to another.

Collapse | Copy Code
  1. sh.CopyAllData("person", "person_new");

Before copying, SQLiteHelper will scan the two tables for match columns. Only columns that exist in both tables will be copied.

16. DropTable

Drop table, delete a table

Collapse | Copy Code
  1. sh.DropTable("person");

17. ShowDatabase

Display attached databases.

Collapse | Copy Code
  1. DataTable dt = sh.ShowDatabase();

18. AttachDatabase, DetachDatabase

Attach or detach a database

Collapse | Copy Code
  1. sh.AttachDatabase("C:\\data2013.sq3", "lastyeardb");
  2. sb.DetachDatabase("lastyeardb");

That's it, guys/girls. Comments are welcome.

SQLite Helper (C#) zt的更多相关文章

  1. sqlite helper

    //-------------------------------------------------------------------------- // // Copyright (c) BUS ...

  2. SQLite Helper (C#) z

    http://www.codeproject.com/Articles/746191/SQLite-Helper-Csharp Introduction I have written a small ...

  3. C#操作SQLite数据库

    SQLite介绍 SQLite is a software library that implements a self-contained, serverless, zero-configurati ...

  4. Android中多表的SQLite数据库(译)

    原文: Android SQLite Database with Multiple Tables 在上一篇教程Android SQLite Database Tutorial中,解释了如何在你的And ...

  5. C# SQLite 创建数据库的方法增删查改语法和命令

    SQLite介绍 SQLite是一个开源.免费的小型RDBMS(关系型数据库),能独立运行.无服务器.零配置.支持事物,用C实现,内存占用较小,支持绝大数的SQL92标准. SQLite数据库官方主页 ...

  6. 安卓APP与智能硬件相结合的简易方案

    第1章 概  述 (作者小波QQ463431476) (来源http://blog.chinaaet.com/zhaocundang/p/5100017645博客) (来源   http://www. ...

  7. Spring JavaMail发送邮件

    JavaMail的介绍 JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口.它是Sun发布的用来处理email的API.它可以方便地执行一些常用的邮件传输.   虽然JavaMail是 ...

  8. HRPlugin For Xcode发布(附源码地址)

    今天给大家介绍的这个插件,是我在IOS平台上开发以来,一些想法的集合体.因为本人时常感觉在开发过程中无论从GOOGLE资料查找和SQL数据库查询,正则表达式测试,SVN等,这些经常要做的操作中,耽误了 ...

  9. 使用Rxjava缓存请求

    最近,我尝试使用RxJava开发了一款闲时备份app.我必须承认,一旦你get到了正确的方式,RxJava几乎感觉就像作弊.一切看起来更简洁,多个请求能够被组合,且非常容易控制.通过在UI线程观察和在 ...

随机推荐

  1. C#和Js 编码和解码方法

    Server.UrlDecode(); Server.UrlEncode(); Server.HtmlDecode(); Server.HtmlEncode();

  2. 1049: [HAOI2006]数字序列 - BZOJ

    Description 现在我们有一个长度为n的整数序列A.但是它太不好看了,于是我们希望把它变成一个单调严格上升的序列.但是不希望改变过多的数,也不希望改变的幅度太大.Input 第一行包含一个数n ...

  3. L​i​n​u​x​环​境​变​量​的​设​置​和​查​看​方​法

    L​i​n​u​x​环​境​变​量​的​设​置​和​查​看​方​法 1. 显示环境变量HOME [root@AY1404171530212980a0Z ~]# echo $HOME /root 2. ...

  4. Extjs布局——layout: 'card'

    先看下此布局的特性: 下面演示一个使用layout: 'card'布局的示例(从API copy过来的)——导航面板(注:导航面板切换下一个或上一个面板实际是导航面板的布局--layout调用指定的方 ...

  5. uva 10069

    简单的dp 但是一个大数加法  套用了末位大牛的类模板 #include <cstdio> #include <cstring> #include <algorithm& ...

  6. [转]掌握 ASP.NET 之路:自定义实体类简介 --自定义实体类和DataSet的比较

    转自: http://www.microsoft.com/china/msdn/library/webservices/asp.net/CustEntCls.mspx?mfr=true 发布日期 : ...

  7. POJ1002487-3279(map)

    http://poj.org/problem?id=1002 题意:是说很多公司用了容易记住的电话号码,例如有英文字母的或者是用了很多连字符或没有连字符的.每个电话号码都有标准模式,而为了统计有没有重 ...

  8. Google Play市场考察报告-2

    接上文,本次继续考察App. (6)CNBETA win8平板客户端 cnBeta是国内少有的科技类资讯网站,在程序员群体中具有很大影响力.面向程序员的软件应用在APP中一向属于少数,然而程序员群体已 ...

  9. [itint5]三数和为0

    http://www.itint5.com/oj/#20 其实是3sum的变种,有重复数字,但是一开始还是写错了.其实是选定一个后,在右边剩余数组里找2sum,找到一组后继续找. #include & ...

  10. linux下添加PATH环境变量

    添加PATH环境变量,第1种方法:[root@lx_web_s1 ~]# export PATH=/usr/local/webserver/mysql/bin:$PATH 再次查看: [root@lx ...