SQLite之C#連接SQLite


SQLite是一個開源、免費的小型的Embeddable RDBMS(關系型數據庫),用C實現,內存占用較小,支持絕大數的SQL92標准,現在已變得越來越流行,它的體積很小,被廣泛應用於各種不同類型的應用中。SQLite已經是世界上布署得最廣泛的SQL數據庫引擎,被用在無以計數的桌面電腦應用中,還有消費電子設備中,如移動電話、掌上電腦和MP3播放器等。

SQLite,是一款輕型的數據庫,是遵守ACID的關聯式數據庫管理系統,它的設計目標是嵌入式的,而且目前已經在很多嵌入式產品中使用了它,它 占用資源非常的低,在嵌入式設備中,可能只需要幾百K的內存就夠了。它能夠支持Windows/Linux/Unix等等主流的操作系統,同時能夠跟很多 程序語言相結合,比如 Tcl、C#、PHP、Java等,還有ODBC接口,同樣比起Mysql、PostgreSQL這兩款開源世界著名的數據庫管理系統來講,它的處理速度 比他們都快。SQLite第一個Alpha版本誕生於2000年5月. 至今已經有10個年頭,SQLite也迎來了一個版本 SQLite 3已經發布。

  官方網站:http://www.sqlite.org/

      詳細簡介:http://baike.baidu.com/view/19310.htm

 

要使用sqlite保存數據,則需要用到SQLite操作驅動的dll,可以在官網下載,安裝完成后,引用安裝目錄下的System.Data.SQLite.dll文件,

可以在我百度網盤下載:sqlite-netFx40-setup-bundle-x64-2010-1.0.96.0.exe

 

 

 

你也可以直接在項目中安裝sqlite,項目會自動添加引用

 

 

 

安裝完成后,你會發現。app.config中會自動生成配置代碼

復制代碼
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3     <configSections>
 4         <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
 5         <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
 6         <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null" />
 7     </configSections>
 8     <system.data>
 9         <DbProviderFactories>
10             <remove invariant="System.Data.SQLite.EF6" />
11             <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" 
type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" /> 12 </DbProviderFactories> 13 </system.data> 14 <entityFramework> 15 <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> 16 <providers> 17 <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 18 <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" /> 19 </providers> 20 </entityFramework> 21 <connectionStrings> 22 <add name="sqlite" connectionString="Data Source=|DataDirectory|\document.db;Pooling=true;FailIfMissing=false" 23 providerName="System.Data.SQLite" /> 24 </connectionStrings> 25 </configuration>
復制代碼

 

 

 

這些步驟完成后,就可以操作sqlite數據庫。如果你鏈接數據庫的時候。提示:

未能加載文件或程序集“System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139”或它的某一個依賴項。試圖加載格式不正確的程序。

這是因為目標平台不匹配, 原因是SQLite下載的平台類型不對造成的,因為你下載的sqlite驅動分x86和x64位,你可以把項目平台改成匹配的,右鍵項目屬性:

 

 

前期准備完成,在編碼前,當然少不了一個工具,來對數據庫進行管理。創建庫、表、執行SQL語句操作,

比如:SQLite Expert Personal 3,Navicat for SQLite等等,

 

SQLite Expert Personal 3界面,

 

我這里使用Navicat for SQLite來管理sqlite,

打開Navicat for SQLite,單擊連接,如圖:

 

連接成功后,創建表,添加數據。

 

我這里創建一個表:document.db,並添加簡單的數據用於測試

 

 

接下來可以在vs中編碼,如果用過sql server,那么sqlite就沒什么難的

 使用原生態的ADO.NET訪問SQLite

  原生態的訪問,就是說直接用connection和command這些對象打開數據庫,然后打開連接,進行數據的操作。

在App.config中配置connectionStrings

1 <connectionStrings>
2         <add name="sqlite" connectionString="Data Source=|DataDirectory|\document.db;Pooling=true;FailIfMissing=false"
3           providerName="System.Data.SQLite" />
4     </connectionStrings>

 

上面的connectionstring配置節的db就是SQLite的數據庫文件,將它放在Web應用的App_Data目錄,|DataDirectory|就代表這個目錄的位置,后面的就是文件名。   剩下的就是我們使用企業庫訪問SQL Server是一樣的了。

到這里。其實有一個盲區。就是App_Data,是web應用中才有,但winform中是沒有的。在winform中DataDirectory被程序弄成了apppath/bin/debug目錄,所以,此時。你需要把document.db賦值到debug目錄下面。

現在來測試是否可以成功訪問數據庫並讀取數據

復制代碼
 1    string sql = "SELECT * FROM userInfo";
 2             //string conStr = "D:/sqlliteDb/document.db";
 3             string connStr = @"Data Source=" + @"D:\sqlliteDb\document.db;Initial Catalog=sqlite;Integrated Security=True;Max Pool Size=10";
 4             using (SQLiteConnection conn = new SQLiteConnection(connStr))
 5             {
 6                 //conn.Open();
 7                 using (SQLiteDataAdapter ap = new SQLiteDataAdapter(sql, conn))
 8                 {
 9                     DataSet ds = new DataSet();
10                     ap.Fill(ds);
11 
12                     DataTable dt = ds.Tables[0];
13                 }
14             }
復制代碼

設置一個斷點,發現已經得到sqlite中的數據

 

如果想讀取app.config中的數據庫連接字符串

復制代碼
 1 string config = System.Configuration.ConfigurationManager.ConnectionStrings["sqlite"].ConnectionString;
 2             using (SQLiteConnection conn = new SQLiteConnection(config))
 3             {
 4                 conn.Open();
 5                 //DbCommand comm = conn.CreateCommand();
 6                 //comm.CommandText = "select * from userinfo";
 7                 //comm.CommandType = CommandType.Text;
 8 
 9                 //conn.Open();
10                 using (SQLiteDataAdapter ap = new SQLiteDataAdapter(sql, conn))
11                 {
12                     DataSet ds = new DataSet();
13                     ap.Fill(ds);
14 
15                     DataTable dt = ds.Tables[0];
16                 }
17             }
復制代碼

 

 

 

使用SQLite.NET訪問SQLite

  SQLite.NET也是一個數據訪問組件,其中的System.Data.SQLite 就好像是.NET自帶的System.Data.SqlClient一樣。里面包含了connection、command等數據訪問的常用對象,只是他們前面都有一個前綴sqlite。

回到之前的app.config。當用NuGet程序包安裝sqlite后。里面自動生成了如下代碼

復制代碼
1 <system.data>
2         <DbProviderFactories>
3             <remove invariant="System.Data.SQLite.EF6" />
4             <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" 
type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" /> 5 </DbProviderFactories> 6 </system.data>
復制代碼

 

即:添加一個DbProviderFactory的創建源,在代碼中就可以使用DbProviderFactory類來創建SQLite的數據訪問對象。

復制代碼
 1 DbProviderFactory fact = DbProviderFactories.GetFactory("System.Data.SQLite.EF6");
 2             using (DbConnection conn = fact.CreateConnection())
 3             {
 4                 conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlite"].ConnectionString;
 5                 conn.Open();
 6                 DbCommand comm = conn.CreateCommand();
 7                 comm.CommandText = "select * from userInfo";
 8                 comm.CommandType = CommandType.Text;
 9                 using (IDataReader reader = comm.ExecuteReader())
10                 {
11                     while (reader.Read())
12                     {
13                         string dd = reader["name"].ToString();
14                     }
15                 }
16             }
復制代碼

同樣測試看結果:

 

 

可以用SQLiteConnection.CreateFile("D:/d.db");直接創建一個數據庫文件

 

 

網上找了一個sqlite幫助類,有需要的可以看下

  View Code

 

 

其他資料:

  http://www.cnblogs.com/virusswb/archive/2010/09/17/SQLite1.html

  http://blog.csdn.net/heqichanggg/article/details/5784839

  http://www.cnblogs.com/luxiaoxun/p/3784729.html

  http://www.cnblogs.com/xugang/archive/2011/04/19/2020713.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM