1. 程式人生 > >c# winform開發 之 SQLLite 資料庫 部署

c# winform開發 之 SQLLite 資料庫 部署

 恰好開發一個winform程式,希望在客戶端儲存一些資訊,在離線狀態下也能夠同步資料庫。本來解決方案是在本地採用xml 檔案進行儲存資料,也很好實現,但是xml檔案操作起來沒有資料庫那麼方便,於是就更改了解決方案,採用SQLLite這個輕量級資料庫。

    1. 軟體工具:visual studio 2008      框架:NET framework 3.5

    2. 資料庫的部署,

點選下載後,安裝就行。(注意:安裝的時候最好不要開著vs2008)

    3. 開啟vs2008,新建一個winform應用程式

    4. 開啟“伺服器資源管理器” 在這裡右擊“資料連線”---->新增連線   ------》更改  -----》更改資料來源為:“SQLLite Database FIle“----->確定 ---->Browse選擇你的資料庫,(注意選擇的檔案一定是以後綴“.db3”結束的,如果你還沒建庫,那麼你就隨便建一個以後綴為"db3"結束的檔案,放到你專案的bin目錄的debug中(很重要,程式釋出的路徑))

    5.OK,SQLLite已經建好了,可以在vs2008中用圖形化介面操作我們的SQLLite庫了,這是多麼棒的事情。

    6.右擊專案名稱 ---- >>> 新增引用--->  新增System.data.SQLite (如果要用LinQ,把System.data.SQLite.Linq也添上)

    7.ok,可以編寫程式碼操作SQLLite資料庫了。新建“SqlLiteHelper.cs”類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;//需要新增using System.Windows.Forms;//需要新增namespace Client
{
    
class SqlLiteHelper
    {

        
#region 連線字串///<summary>/// 連線資料庫字串
        
///</summary>///<returns></returns>publicstatic String getSQLiteConn()
        {
            
return"Data Source=
"+ Application.StartupPath +"\\statistics.db3";  //獲取絕對路徑,看好了,別搞錯了
        }
       
#endregion publicstaticvoid insert(String ip)
        {
 
           SQLiteConnection conn =new SQLiteConnection(SqlLiteHelper.getSQLiteConn());
            SQLiteCommand cmd 
=new SQLiteCommand();//很熟悉把             DateTime StartComputerTime = DateTime.Now;
            cmd.Connection 
= conn;
            cmd.CommandText 
="insert into TimeBill(id,ip,StartComputerTime,logoutTime) values(@id ,@ip,@StartComputerTime,0)";
            cmd.Parameters.AddWithValue(
"@ip", ip);
            cmd.Parameters.AddWithValue(
"@id"1);
            cmd.Parameters.AddWithValue(
"@StartComputerTime", StartComputerTime.ToString());
            
using (conn)
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }

    }
}
複製程式碼

    8.ok。如果出現異常為“no such table”,那麼錯誤一定出在路徑上,路徑一定是絕對路徑。

    “no such table ”直譯為“找不到表”,原來SQLLite在定義的路徑下找不到資料庫時,它會自動建設一個空的SQLLite庫,那麼找到的就是這個空庫,自然就沒有表了,所以就會報告“no such table "的錯誤。解決辦法:仔細修改路徑。

    注意:編寫SQLLite的sql語句時,只有部分sql函式在SQLLite中可以用,目前用到的getdate()函式不能用。 

    些此文目的:希望能為初學者節省點時間!彎路必不可少,我們慢慢走過,體驗程式設計之快!