新文章

2012年1月12日 星期四

[C#]使用SQLlite實作

寫軟體常常要顧慮資料處理的問題,若是網頁則無需困擾免費的MySQL就可以用,無須擔心使用者的問題,因為資料處理是在本機Server端。


若是寫單機程式就要考慮這個問題了(資料處理在使用者端點),雖然簡易資料用txt,excel就可以解決,但是複雜的資料處理就要考慮資料庫了,access看似很平常但就是有部分使用者沒有的問題,剛好自己遇到這個問題,強烈推薦SQLite,他是屬於embeded DB,Client端無須考慮是否有安裝該DB的問題,非常便於攜帶且容量極小並符合現在大部分主流平台和免費!

1.先下載SQLite.NET的DLL參考: http://goo.gl/cBl7w
此版本為SQLite-1.0.66.0 欲取得最新版本請至: http://goo.gl/RXQYf

2.將下載回來的檔案解壓縮後打開VS專案在參考中加入System.Data.SQLite和System.Data.SQLite.Linq

3.程式區段
using System.Data.SQLite;  

namespace SQLITE
{
    public partial class Form1 : Form
    {
        private SQLiteConnection sqlite_conn;
        private SQLiteCommand sqlite_cmd;  

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            sqlite_conn = new SQLiteConnection("Data source=database.db");

            // Open
            sqlite_conn.Open();

            // 要下任何命令先取得該連結的執行命令物件
            sqlite_cmd = sqlite_conn.CreateCommand();

            // 要下的命令新增一個表
            sqlite_cmd.CommandText = "CREATE TABLE test (id integer primary key, text varchar(10));";

            sqlite_cmd.ExecuteNonQuery();

            // 插入一筆
            sqlite_cmd.CommandText = "INSERT INTO test (id, text) VALUES (1, '測試1');";

            sqlite_cmd.ExecuteNonQuery();
            // 查詢剛新增的表test
            sqlite_cmd.CommandText = "SELECT * FROM test";

            // 執行查詢塞入 sqlite_datareader
            SQLiteDataReader sqlite_datareader = sqlite_cmd.ExecuteReader();

            // 一筆一筆列出查詢的資料
            while (sqlite_datareader.Read())
            {
                // Print out the content of the text field:
                String s = sqlite_datareader["text"].ToString();
                MessageBox.Show(s);
            }
   //結束
            sqlite_conn.Close();
        }

小叮嚀:
避免發佈到客戶端後程式開不起來,請記得設定參考中System.Data.SQLite和System.Data.SQLite.Linq屬性:[複製到本機=True]

沒有留言:

張貼留言