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;
相关文章
相关标签/搜索