有問題歡迎留言!!!html
個人環境配置:windows 64,VS,SQLite(點擊下載),System.Data.SQLite.DLL(點擊下載)。 sql
1.在VS中新建一個控制檯應用程序,以下圖數據庫
2.添加引用windows
將下載的System.Data.SQLite.DLL複製到新建項目的路徑下服務器
在VS中找到項目,右鍵選擇添加引用架構
瀏覽到dll路徑下,添加進來。app
代碼中添加less
using System.Data.SQLite;
添加類庫CSQLiteHelper,用於存放SQLite操做方法(此代碼原文連接. http://www.javashuo.com/article/p-kijbyjmq-hx.html)dom
具體代碼ide
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data.SQLite; 6 using System.Data; 7 using System.Xml; 8 using System.Text.RegularExpressions; 9 using System.IO; 10 11 namespace CSharp_SQLite 12 { 13 public class CSQLiteHelper 14 { 15 private string _dbName = ""; 16 private SQLiteConnection _SQLiteConn = null; //鏈接對象 17 private SQLiteTransaction _SQLiteTrans = null; //事務對象 18 private bool _IsRunTrans = false; //事務運行標識 19 private string _SQLiteConnString = null; //鏈接字符串 20 private bool _AutoCommit = false; //事務自動提交標識 21 22 public string SQLiteConnString 23 { 24 set { this._SQLiteConnString = value; } 25 get { return this._SQLiteConnString; } 26 } 27 28 public CSQLiteHelper(string dbPath) 29 { 30 this._dbName = dbPath; 31 this._SQLiteConnString = "Data Source=" + dbPath; 32 } 33 34 /// <summary> 35 /// 新建數據庫文件 36 /// </summary> 37 /// <param name="dbPath">數據庫文件路徑及名稱</param> 38 /// <returns>新建成功,返回true,不然返回false</returns> 39 static public Boolean NewDbFile(string dbPath) 40 { 41 try 42 { 43 SQLiteConnection.CreateFile(dbPath); 44 return true; 45 } 46 catch (Exception ex) 47 { 48 throw new Exception("新建數據庫文件" + dbPath + "失敗:" + ex.Message); 49 } 50 } 51 52 53 /// <summary> 54 /// 建立表 55 /// </summary> 56 /// <param name="dbPath">指定數據庫文件</param> 57 /// <param name="tableName">表名稱</param> 58 static public void NewTable(string dbPath, string tableName) 59 { 60 61 SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath); 62 if (sqliteConn.State != System.Data.ConnectionState.Open) 63 { 64 sqliteConn.Open(); 65 SQLiteCommand cmd = new SQLiteCommand(); 66 cmd.Connection = sqliteConn; 67 cmd.CommandText = "CREATE TABLE " + tableName + "(Name varchar,Team varchar, Number varchar)"; 68 cmd.ExecuteNonQuery(); 69 } 70 sqliteConn.Close(); 71 } 72 /// <summary> 73 /// 打開當前數據庫的鏈接 74 /// </summary> 75 /// <returns></returns> 76 public Boolean OpenDb() 77 { 78 try 79 { 80 this._SQLiteConn = new SQLiteConnection(this._SQLiteConnString); 81 this._SQLiteConn.Open(); 82 return true; 83 } 84 catch (Exception ex) 85 { 86 throw new Exception("打開數據庫:" + _dbName + "的鏈接失敗:" + ex.Message); 87 } 88 } 89 90 /// <summary> 91 /// 打開指定數據庫的鏈接 92 /// </summary> 93 /// <param name="dbPath">數據庫路徑</param> 94 /// <returns></returns> 95 public Boolean OpenDb(string dbPath) 96 { 97 try 98 { 99 string sqliteConnString = "Data Source=" + dbPath; 100 101 this._SQLiteConn = new SQLiteConnection(sqliteConnString); 102 this._dbName = dbPath; 103 this._SQLiteConnString = sqliteConnString; 104 this._SQLiteConn.Open(); 105 return true; 106 } 107 catch (Exception ex) 108 { 109 throw new Exception("打開數據庫:" + dbPath + "的鏈接失敗:" + ex.Message); 110 } 111 } 112 113 /// <summary> 114 /// 關閉數據庫鏈接 115 /// </summary> 116 public void CloseDb() 117 { 118 if (this._SQLiteConn != null && this._SQLiteConn.State != ConnectionState.Closed) 119 { 120 if (this._IsRunTrans && this._AutoCommit) 121 { 122 this.Commit(); 123 } 124 this._SQLiteConn.Close(); 125 this._SQLiteConn = null; 126 } 127 } 128 129 /// <summary> 130 /// 開始數據庫事務 131 /// </summary> 132 public void BeginTransaction() 133 { 134 this._SQLiteConn.BeginTransaction(); 135 this._IsRunTrans = true; 136 } 137 138 /// <summary> 139 /// 開始數據庫事務 140 /// </summary> 141 /// <param name="isoLevel">事務鎖級別</param> 142 public void BeginTransaction(IsolationLevel isoLevel) 143 { 144 this._SQLiteConn.BeginTransaction(isoLevel); 145 this._IsRunTrans = true; 146 } 147 148 /// <summary> 149 /// 提交當前掛起的事務 150 /// </summary> 151 public void Commit() 152 { 153 if (this._IsRunTrans) 154 { 155 this._SQLiteTrans.Commit(); 156 this._IsRunTrans = false; 157 } 158 } 159 160 161 } 162 }
此時運行會報錯,
警告 所生成項目的處理器架構「MSIL」與引用「System.Data.SQLite」的處理器架構「x86」不匹配。這種不匹配可能會致使運行時失敗。請考慮經過配置管理器更改您的項目的目標處理器架構,以使您的項目與引用間的處理器架構保持一致,或者爲引用關聯一個與您的項目的目標處理器架構相符的處理器架構。
修改項目屬性:x86。
再次運行,無誤。
SQLite 是文件型的數據庫,後綴名能夠是".db3"、".db"或者「.sqlite」,甚至能夠由你決定它的後綴。其中前3個類型是SQLite默認類型。
新建一個數據庫文件,代碼以下
1 /// <summary> 2 /// 新建數據庫文件 3 /// </summary> 4 /// <param name="dbPath">數據庫文件路徑及名稱</param> 5 /// <returns>新建成功,返回true,不然返回false</returns> 6 static public Boolean NewDbFile(string dbPath) 7 { 8 try 9 { 10 SQLiteConnection.CreateFile(dbPath); 11 return true; 12 } 13 catch (Exception ex) 14 { 15 throw new Exception("新建數據庫文件" + dbPath + "失敗:" + ex.Message); 16 } 17 }
1 /// <summary> 2 /// 建立表 3 /// </summary> 4 /// <param name="dbPath">指定數據庫文件</param> 5 /// <param name="tableName">表名稱</param> 6 static public void NewTable(string dbPath, string tableName) 7 { 8 9 SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath); 10 if (sqliteConn.State != System.Data.ConnectionState.Open) 11 { 12 sqliteConn.Open(); 13 SQLiteCommand cmd = new SQLiteCommand(); 14 cmd.Connection = sqliteConn; 15 cmd.CommandText = "CREATE TABLE " + tableName + "(Name varchar,Team varchar, Number varchar)"; 16 cmd.ExecuteNonQuery(); 17 } 18 sqliteConn.Close(); 19 }
例子:建立一個數據庫文件 NBA.db3
而後建立表Stars,再建立表的列,Name,Team,Number。
1 class Program 2 { 3 private static string dbPath = @"d:\NBA.db3"; 4 static void Main(string[] args) 5 { 6 //建立一個數據庫db文件 7 CSQLiteHelper.NewDbFile(dbPath); 8 //建立一個表 9 string tableName = "Stars"; 10 CSQLiteHelper.NewTable(dbPath, tableName); 11 } 12 }
看下效果,數據庫文件NBA的表Stars中有Name,Team和Number字段
接下來,使用SQLite 的 INSERT INTO 語句用於向數據庫的某個表中添加新的數據行。
先在Main()方法中建立一些數據。
1 List<object[]> starsDatas = new List<object[]>(); 2 starsDatas.Add(new object[] { "Garnett", "Timberwolves", "21" }); 3 starsDatas.Add(new object[] { "Jordan", "Bulls", "23" }); 4 starsDatas.Add(new object[] { "Kobe", "Lakers", "24" }); 5 starsDatas.Add(new object[] { "James", "Cavaliers", "23" }); 6 starsDatas.Add(new object[] { "Tracy", "Rockets", "1" }); 7 starsDatas.Add(new object[] { "Carter", "Nets", "15" });
將數據插入到表單中
1 private static void AddStars(List<object[]> stars) 2 { 3 CSQLiteHelper sqlHelper = new CSQLiteHelper(dbPath); 4 sqlHelper.OpenDbConn(); 5 string commandStr = "insert into Stars(Name,Team,Number) values(@name,@team,@number)"; 6 foreach (var item in stars) 7 { 8 if (isExist("Name", item[0].ToString())) 9 { 10 Console.WriteLine(item[0] + "的數據已存在!"); 11 continue; 12 } 13 else 14 { 15 sqlHelper.ExecuteNonQuery(commandStr, item); 16 Console.WriteLine(item[0] + "的數據已保存!"); 17 Console.ReadKey(); 18 } 19 } 20 sqlHelper.CloseDbConn(); 21 Console.ReadKey(); 22 23 }
效果以下:
SQLite 的 SELECT 語句用於從 SQLite 數據庫表中獲取數據,以結果表的形式返回數據。這些結果表也被稱爲結果集。
一個簡單的例子:查詢一個球星所在的球隊。
輸入球星的名字,輸出球隊。
1 private static void Team(string name) 2 { 3 CSQLiteHelper sqliteHelper = new CSQLiteHelper(dbPath); 4 sqliteHelper.OpenDbConn(); 5 string commandText = @"select * from Stars where Name ='" + name+"'"; 6 DataTable dt = sqliteHelper.Query(commandText).Tables[0]; 7 if (dt.Rows.Count == 0) 8 { 9 Console.WriteLine("查無此人!"); 10 Console.ReadLine(); 11 sqliteHelper.CloseDbConn(); 12 return; 13 } 14 string team = dt.Rows[0]["Team"].ToString(); 15 sqliteHelper.CloseDbConn(); 16 Console.WriteLine(name + "--" + team); 17 Console.ReadKey(); 18 }
1 static void Main(string[] args) 2 { 3 Console.WriteLine("請輸入一個Star:"); 4 string name = Console.ReadLine(); 5 Team(name); 6 }
效果以下
SQLite 的 DELETE 語句用於刪除表中已有的記錄。能夠使用帶有 WHERE 子句的 DELETE 查詢來刪除選定行,不然全部的記錄都會被刪除。
1 private static void Delete(string name) 2 { 3 CSQLiteHelper sqliteHelper = new CSQLiteHelper(dbPath); 4 sqliteHelper.OpenDbConn(); 5 string commandtext = "delete from Stars where Name = '" + name + "'"; 6 sqliteHelper.ExecuteNonQuery(commandtext); 7 sqliteHelper.CloseDbConn(); 8 Console.WriteLine(name + "被刪除!"); 9 }
注意:delete語句與select語句不一樣,delete後直接跟from,不能寫成:
"delete * from Stars where [condition];
調用一下
Console.WriteLine("刪除球星:"); string starName = Console.ReadLine(); Delete(starName);
刪除前:
刪除後:
運算符是一個保留字或字符,主要用於 SQLite 語句的 WHERE 子句中執行操做,如比較和算術運算。
運算符用於指定 SQLite 語句中的條件,並在語句中鏈接多個條件。
能夠直接在SQLite語句中加入運算符,= - * / % > < = >= <= 等等
例:
下面代碼是首先插入一些NBA球員的信息,而後篩選出球衣號碼大於10的球員:
1 using System; 2 using System.Collections.Generic; 3 using System.Data.SQLite; 4 using System.Data; 5 using System.IO; 6 using System.Data.Common; 7 using System.Diagnostics; 8 9 10 namespace CSharp_SQLite 11 { 12 class Program 13 { 14 15 static void Main(string[] args) 16 { 17 string dbPath = "NBAStars.nba"; 18 Stopwatch timer = new Stopwatch(); 19 timer.Start(); 20 CSQLiteHelper sqlhelper = new CSQLiteHelper(dbPath); 21 sqlhelper.OpenDbConn(); 22 sqlhelper.BeginTransaction(); 23 sqlhelper.ExecuteNonQuery("delete from Stars"); 24 #region 球員信息 25 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Michael Jordan','Bulls','23')"); 26 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('James Harden','Rockets','13')"); 27 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Lebron James','Cavaliers','23')"); 28 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Tracy Mcgrady','Rockets','1')"); 29 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Yao Ming','Rockets','11')"); 30 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Kevin Garnett','Timberwolves','21')"); 31 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Tim Duncan','Supers','21')"); 32 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Vince Carter','Nets','15')"); 33 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Michael Carter Williams','76ers','10')"); 34 #endregion 35 sqlhelper.Commit(); 36 sqlhelper.CloseDbConn(); 37 timer.Stop(); 38 Console.WriteLine("初始化數據庫表單用時:" + timer.Elapsed); 39 40 41 CSQLiteHelper sqlHelper = new CSQLiteHelper(dbPath); 42 sqlHelper.OpenDbConn(); 43 sqlHelper.BeginTransaction(); 44 DataTable dt = sqlHelper.Query("select Name, Number from Stars where Number > 10").Tables[0]; 45 sqlHelper.Commit(); 46 sqlHelper.CloseDbConn(); 47 Console.WriteLine("球衣號碼大於10的球員有:"); 48 for (int i = 0; i < dt.Rows.Count; i++) 49 { 50 Console.WriteLine(dt.Rows[i]["Name"] + "\t" + dt.Rows[i]["Number"]); 51 } 52 Console.ReadLine(); 53 } 54 55 } 56 57 }
結果以下:
若想輸出這些球員的球衣號碼,則應該在select語句修改成
DataTable dt = sqlHelper.Query("select Name, Number from Stars where Number > 10").Tables[0];
將輸出修改成
Console.WriteLine(dt.Rows[i]["Name"] + "\t" + dt.Rows[i]["Number"]);
結果以下:
注:select語句中儘可能不要使用select * from,那樣會影響效率。
SQLite 的 LIKE 運算符是用來匹配通配符指定模式的文本值。若是搜索表達式與模式表達式匹配,LIKE 運算符將返回真(true),也就是 1。這裏有兩個通配符與 LIKE 運算符一塊兒使用:
百分號(%)表明零個、一個或多個數字或字符。下劃線(_)表明一個單一的數字或字符。這些符號能夠被組合使用。
% 和 _ 的基本語法以下:
SELECT column_list FROM table_name WHERE column LIKE 'XXXX%' or SELECT column_list FROM table_name WHERE column LIKE '%XXXX%' or SELECT column_list FROM table_name WHERE column LIKE 'XXXX_' or SELECT column_list FROM table_name WHERE column LIKE '_XXXX' or SELECT column_list FROM table_name WHERE column LIKE '_XXXX_'
您能夠使用 AND 或 OR 運算符來結合 N 個數量的條件。在這裏,XXXX 能夠是任何數字或字符串值。
例
咱們在球員中篩選出名字中包含James的球員
1 using System; 2 using System.Collections.Generic; 3 using System.Data.SQLite; 4 using System.Data; 5 using System.IO; 6 using System.Data.Common; 7 using System.Diagnostics; 8 9 10 namespace CSharp_SQLite 11 { 12 class Program 13 { 14 15 static void Main(string[] args) 16 { 17 string dbPath = "NBAStars.nba"; 18 Stopwatch timer = new Stopwatch(); 19 timer.Start(); 20 CSQLiteHelper sqlhelper = new CSQLiteHelper(dbPath); 21 sqlhelper.OpenDbConn(); 22 sqlhelper.BeginTransaction(); 23 sqlhelper.ExecuteNonQuery("delete from Stars"); 24 #region 球員信息 25 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Michael Jordan','Bulls','23')"); 26 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('James Harden','Rockets','13')"); 27 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Lebron James','Cavaliers','23')"); 28 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Tracy Mcgrady','Rockets','1')"); 29 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Yao Ming','Rockets','11')"); 30 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Kevin Garnett','Timberwolves','21')"); 31 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Tim Duncan','Supers','21')"); 32 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Vince Carter','Nets','15')"); 33 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Michael Carter Williams','76ers','10')"); 34 #endregion 35 sqlhelper.Commit(); 36 sqlhelper.CloseDbConn(); 37 timer.Stop(); 38 Console.WriteLine("初始化數據庫表單用時:" + timer.Elapsed); 39 40 41 CSQLiteHelper sqlHelper = new CSQLiteHelper(dbPath); 42 sqlHelper.OpenDbConn(); 43 sqlHelper.BeginTransaction(); 44 DataTable dt = sqlHelper.Query("select Name, Number from Stars where Name like '%James%'").Tables[0]; 45 sqlHelper.Commit(); 46 sqlHelper.CloseDbConn(); 47 Console.WriteLine("名字中包含James的球員有:"); 48 for (int i = 0; i < dt.Rows.Count; i++) 49 { 50 Console.WriteLine(dt.Rows[i]["Name"] + "\t" + dt.Rows[i]["Number"]); 51 } 52 Console.ReadLine(); 53 } 54 55 } 56 57 }
其中第44行代碼 DataTable dt = sqlHelper.Query("select Name, Number from Stars where Name like '%James%'").Tables[0];
%James%表示前面和後面包含零個、一個或多個數字或字符,也就是包含名字內James
運行結果以下
前言:
這一段來自SQLite官網
SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactionalSQL database engine. The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private. SQLite is the most widely deployed database in the world with more applications than we can count, including several high-profile projects.
SQLite 是一個軟件庫,實現了自給自足的、無服務器的、零配置的、事務性的 SQL 數據庫引擎。SQLite 源代碼不受版權限制。SQLite 是在世界上最普遍部署的 SQL 數據庫引擎。SQLite是世界上應用最普遍的數據庫,擁有着不可勝數的應用,包括備受矚目的項目。
本文版權歸做者和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。