0%

WP7开发 Sqlite数据库的使用 解决Unable open the database

WP7本身不支持Sqlite数据库,但我们可以添加第三方组件让它支持Sqlite. 首先在项目中添加引用Community.CsharpSqlite.WP.dll,我会放后面让大家下载,我下了有几天了,是源码,我也找不回原网址了,所以就编译了一下,直接引用就可以了. 另外,原版在使用从外部添加的数据库时(即不是在程序中生成的数据库),会提示”Unable open the database”,我改了一下,已经解决该问题.经测试,不支持like语法,就是不支持模糊查询,这个有点郁闷。 解决方法:打开os_win_c.cs,找到第795行:

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

替换为:

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

下面说说具体的使用方法,只详细介绍select读取数据,其他的没有返回,很简单. 假设数据库为db.db,表为station,字段为station_name. 执行Sql后,返回的是一个枚举类型,我们要先定义一个存放返回数据的类:

    public class Train
    {
        public Train() { }

        string _name;
        public string station_name
            //属性名必须与列名相同
        {
            get { return _name; }
            set { _name = value; }
        }

    }

因为只读station_name,所以只有一个属性. 读取数据库并显示在ListBox上:

            SQLiteConnection db = new SQLiteConnection("db.db");
            //连接数据库,如果不存在,会自动创建,我事先已经拷了一个进去,所以可以下面的select操作
            //数据库是使用IsolatedStorageFile存取的,可以使用IsolatedStorageFile复制,删除等
            db.Open();
            //打开数据库
            SQLiteCommand cmd=db.CreateCommand("select station_name from station limit 100");
            IEnumerable lst = cmd.ExecuteQuery();
            //返回Train类型的枚举
            //非select语句,使用cmd.ExecuteNonQuery();
            List s = new List();
            
            foreach (Train o in lst)
            {
                s.Add(o.station_name);
            }
            listBox1.ItemsSource = s;
            //显示在ListBox上
            
            db.Dispose();
            db = null;
            //释放资源

ListBox的SelectedItem属性返回的是Train类的实例,但需要强制转换:

Train train=(Train)listBox1.SelectedItem;

Community.CsharpSqlite.WP.dll下载: [download id=”27”]