WP7開發 Sqlite數據庫的使用 解決Unable open the database

WP7自己不支持Sqlite數據庫,但咱們能夠添加第三方組件讓它支持Sqlite. 首先在項目中添加引用Community.CsharpSqlite.WP.dll,我會放後面讓你們下載,我下了有幾天了,是源碼,我也找不回原網址了,因此就編譯了一下,直接引用就能夠了. 另外,原版在使用從外部添加的數據庫時(即不是在程序中生成的數據庫),會提示」Unable open the database」,我改了一下,已經解決該問題.經測試,不支持like語法,就是不支持模糊查詢,這個有點鬱悶。 解決方法:打開os_win_c.cs,找到第795行:數據庫

1
pFile.fs = new IsolatedStorageFileStream(zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, store);

替換爲:測試

1
pFile.fs = new IsolatedStorageFileStream(zConverted, FileMode.OpenOrCreate, dwDesiredAccess, dwShareMode, store);

下面說說具體的使用方法,只詳細介紹select讀取數據,其餘的沒有返回,很簡單. 假設數據庫爲db.db,表爲station,字段爲station_name. 執行Sql後,返回的是一個枚舉類型,咱們要先定義一個存放返回數據的類:spa

1
2
3
4
5
6
7
8
9
10
11
12
13
    public class Train
    {
        public Train() { }
 
        string _name;
        public string station_name
            //屬性名必須與列名相同
        {
            get { return _name; }
            set { _name = value; }
        }
 
    }

由於只讀station_name,因此只有一個屬性. 讀取數據庫並顯示在ListBox上:code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
            SQLiteConnection db = new SQLiteConnection("db.db");
            //鏈接數據庫,若是不存在,會自動建立,我事先已經拷了一個進去,因此能夠下面的select操做
            //數據庫是使用IsolatedStorageFile存取的,能夠使用IsolatedStorageFile複製,刪除等
            db.Open();
            //打開數據庫
            SQLiteCommand cmd=db.CreateCommand("select station_name from station limit 100");
            IEnumerable<Train> lst = cmd.ExecuteQuery<Train>();
            //返回Train類型的枚舉
            //非select語句,使用cmd.ExecuteNonQuery();
            List<string> s = new List<string>();
 
            foreach (Train o in lst)
            {
                s.Add(o.station_name);
            }
            listBox1.ItemsSource = s;
            //顯示在ListBox上
 
            db.Dispose();
            db = null;
            //釋放資源

ListBox的SelectedItem屬性返回的是Train類的實例,但須要強制轉換:資源

1
Train train=(Train)listBox1.SelectedItem;
相關文章
相關標籤/搜索