SQLite是一個簡易的資料庫系統,開放原始碼,可以直接把SQLite綁在程式裡使用,FireFox及Android等軟體也都有內建SQLite。SQLite不需要安裝,看起來就只是一個檔案而已,也可以使用memory模式,讓它存在記憶體中而不需要建立一個檔案存放。
SQLite支援的SQL指令:http://www.sqlite.org/lang_corefunc.html
C#要連接SQLite可以使用open source的System.Data.SQLite,它是一個基於ADO.Net所做與SQLite的溝通介面,目前支援到.net framework 3.5。可於sourceforge下載其dll來使用,就可以了。
下方的範例是介紹如何在Csharp下使用ADO.NET連接與操作SQLite,包含了自動產生SQLite檔案與DataGridView使用class binding datasource方法。
一、建立一個專案,並先將其儲存起來
(需要先建置專案才能使用專案裡的class當做datasource)


二、改變專案使用的Framework
在專案節點上選擇屬性

把目標Framework(G):改成.NET Framework 3.5以下

告知需要重新啟動專案

三、加入System.Data.SQLite的Dll當做參考
在專案裡的參考節點上按右鍵選加入參考(R)….

找到DLL加入

在參考的節點上可以看到System.Data.SQLite已加入成功
因為原本專案為.NET Framework 4被降為3.5,所以會多出一個無法使用的參考Microsoft CSharp,此時可順便移除掉它。

四、建立相容模式
SQLite ADO.NET是建立於版本v2.0.50727,所以在比較高的版本會有相容性問題,所以修改app.config或web.config來使其相容使用。
ps.有一說可以在.NET Framework 4.0修改設定則可以使用SQLite ADO.NET

在startup的tag上加上屬性
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v2.0.50727"/> </startup>
在範列裡我們會使用到二種建立SQLite Connection的方法,其中一種為DbProvider,所以需要使用到以下tag內容,放在configuration內就可以了,如果不使用此種DbProvider方法,也可不加。
<system.data> <DbProviderFactories> <remove invariant="System.Data.SQLite"/> <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite"/> </DbProviderFactories> </system.data>

五、建立取得Connection的程式與需要使用的class

Db.css
以下是使用DbOroviderFactory的方法建立Connection
private static DbProviderFactory fact = DbProviderFactories.GetFactory("System.Data.SQLite"); public static DbConnection getConnection()
以下是直接使用new SQLiteConnection來建立連線
public static SQLiteConnection getConnection2()
使用以下語法可以建立SQLite檔案
SQLiteConnection.CreateFile("db/db.s3db");
SQLite在使用時它的ConnectionString “db/db.s3db”,db為其目錄,而db.s3db為其檔案名稱。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Common; using System.Data.SQLite; using System.IO; namespace SQLiteCon { class Db { private static DbProviderFactory fact = DbProviderFactories.GetFactory("System.Data.SQLite"); public static DbConnection getConnection() { if (!Directory.Exists("db")) { Directory.CreateDirectory("db"); } //檔案不存在時就建立 if (!File.Exists("db/db.s3db")) { //自動建立SQLite檔案 SQLiteConnection.CreateFile("db/db.s3db"); } DbConnection cnn = fact.CreateConnection(); cnn.ConnectionString = "Data Source=db/db.s3db"; return cnn; } public static SQLiteConnection getConnection2() { if (!Directory.Exists("db")) { Directory.CreateDirectory("db"); } if (!File.Exists("db/db.s3db")) SQLiteConnection.CreateFile("db/db.s3db"); return new SQLiteConnection("Data Source=db/db.s3db"); } } }
Class1.cs
提供一個class專門來承載資料內容mytest
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using System.Data.Common; namespace SQLiteCon { //使用SQLiteConnection public class mytestnList2 { //利用資料庫查詢把內容查出後存到List的泛型裡 public List<mytest> getAllList() { List<mytest> list = new List<mytest>(); SQLiteConnection conn = Db.getConnection2(); conn.Open(); try { String sql = "select * from mytest"; SQLiteCommand com = conn.CreateCommand(); com.CommandText = sql; SQLiteDataReader reader = com.ExecuteReader(); while (reader.Read()) { mytest idc = new mytest(); idc.item_id = reader.GetString(0); idc.item_name = reader.GetString(1); list.Add(idc); } } catch (Exception ex) { Console.WriteLine(ex); } finally { conn.Close(); } return list; } } //使用DbConnection public class mytestnList { //利用資料庫查詢把內容查出後存到List的泛型裡 public List<mytest> getAllList() { List<mytest> list = new List<mytest>(); DbConnection conn = Db.getConnection(); conn.Open(); try { String sql = "select * from mytest"; DbCommand com = conn.CreateCommand(); com.CommandText = sql; DbDataReader reader = com.ExecuteReader(); while (reader.Read()) { mytest idc = new mytest(); idc.item_id = reader.GetString(0); idc.item_name = reader.GetString(1); list.Add(idc); } } catch (Exception ex) { Console.WriteLine(ex); } finally { conn.Close(); } return list; } } //資料型態與名稱 public class mytest { public String item_id { set; get; } public String item_name { set; get; } } }
六、建立顯示及操作畫面

把DataGridView的DataSource綁定到bindingSource,二組各自綁定一個bindingSource

建置方案,如此class才會被編譯成dll,在使用資料組態來源精靈時才可以看到

把二組的bindingSource都設定其DataSource,利用加入專案資料來源來建立

類型選擇”物件”

然後選擇先寫好的class myetest


另一組則可直接選取,不需要再使用精靈

畫面已經顯示clas裡所定義的欄位,可以自行修改header的名稱來對應

再來針對四個button建立click event的程式
//移除table private void button1_Click(object sender, EventArgs e) { try { using (DbConnection con = Db.getConnection()) { con.Open(); DbCommand cmd = con.CreateCommand(); cmd.CommandText = "drop table mytest"; cmd.ExecuteNonQuery(); con.Close(); } } catch (SQLiteException) { }; } //建立table private void button2_Click(object sender, EventArgs e) { try { using (DbConnection con = Db.getConnection()) { con.Open(); DbCommand cmd = con.CreateCommand(); cmd.CommandText = "create table mytest(item_id TEXT,item_name TEXT);"; cmd.ExecuteNonQuery(); con.Close(); } } catch (SQLiteException) { }; } //新增二筆資料,當測試 private void button3_Click(object sender, EventArgs e) { try { using (DbConnection con = Db.getConnection()) { con.Open(); DbCommand cmd = con.CreateCommand(); cmd.CommandText = "insert into mytest(item_id ,item_name ) values('111','中文');"; cmd.ExecuteNonQuery(); cmd.CommandText = "insert into mytest(item_id ,item_name ) values('222','abc');"; cmd.ExecuteNonQuery(); con.Close(); } } catch (SQLiteException) { }; } //載入資料到DataSource,則form的GridView就可以看到資料了 private void button4_Click(object sender, EventArgs e) { List<mytest> list = (new mytestnList()).getAllList(); bindingSource1.DataSource = list; List<mytest> list2 = (new mytestnList2()).getAllList(); bindingSource2.DataSource = list2; }
七、執行結果
原本在目錄裡並沒有db/db.s3db的目錄及檔案

由上而下操作後,可以看到GridView裡有了二筆資料

再查看目錄裡已經自動建立SQLite的檔案了

One thought to “Csharp使用ADO.NET操作SQLite”