Windows Phone 7 Perst嵌入式數(shù)據(jù)庫的學習
WP7只有本地存儲,自身是不帶數(shù)據(jù)庫存儲的,所以想要在WP7上使用數(shù)據(jù)庫只能通過使用第三方的嵌入式數(shù)據(jù)庫。Perst 是一個簡單,快速,便捷,面向?qū)ο筮m合Java與.NET的數(shù)據(jù)庫,它在嵌入式數(shù)據(jù)庫領(lǐng)域是鼎鼎有名的,并且其代碼是開源的,我們可以在它的官方網(wǎng)站上下載該數(shù)據(jù)庫的所有的代碼。
官方網(wǎng)站www.mcobject.com/perst_eval
下面是Perst數(shù)據(jù)庫在Windows Phone 7上使用的一些基本的語法的簡單總結(jié):
1、創(chuàng)建數(shù)據(jù)庫
- Storage storage = StorageFactory.Instance.CreateStorage(); //創(chuàng)建Perst存儲Storage實例
- storage.Open( "PerstDemoDB.dbs"); // 打開Storage
- Database DB = new Database(storage); //使用上面初始化的Storage實例創(chuàng)建數(shù)據(jù)庫
2、創(chuàng)建數(shù)據(jù)庫面向?qū)ο蟮念?作用相當于關(guān)系數(shù)據(jù)庫的表)
以下是代碼片段:
- //創(chuàng)建一個數(shù)據(jù)庫存儲的面向?qū)ο蟮念惖幕?nbsp;要繼承Perst.Persistent基類
- public class User: Perst.Persistent
- {
- //定義字段
- //Perst使用反射來獲取對象的值 需要在字段的前面加上[FullTextIndexable]標示
- [FullTextIndexable]
- public long id;
- [FullTextIndexable]
- public string name;
- ……
- public long Id
- {
- get { return id; }
- set { id= value; }
- }
- ……
- public User(long Id, string name)
- {
- id = id;
- name = name;
- }
- public override void OnLoad()
- {
- base.OnLoad();
- }
- //獲取數(shù)據(jù)庫對象 一般會將數(shù)據(jù)庫定義在App里面
- protected static Database DB
- {
- get { return ((App)Application.Current).DB; }
- }
- public override void Deallocate()
- {
- DB.DeleteRecord(this);//刪除記錄
- }
- public void Save()
- {
- Store();//保存 相當于保存表
- DB.UpdateFullTextIndex(this);
- }
- }
3、添加記錄
以下是代碼片段:
- User user= new User(1, "名字");
- DB.AddRecord(user);
- DB.Storage.Commit();
4、修改記錄
以下是代碼片段:
- user.Id=2
- user.Save();
5、刪除記錄
以下是代碼片段:
- user.Deallocate();
- DB.Storage.Commit();
6、查詢數(shù)據(jù)庫
根據(jù)唯一的oid查詢記錄 oid是Perst數(shù)據(jù)庫為每一個類的對象分配的一個唯一的值
- User user= DB.Select("oid = " + this.NavigationContext.QueryString["oid"]).FirstOrDefault();
模糊查詢
以下是代碼片段:
- // 查詢所有包含了tbSearch.Text.ToLower()的結(jié)果FullTextSearchResult
- FullTextSearchResult prefixes = DB.SearchPrefix(tbSearch.Text.ToLower(), 1000, 4000, false);
- ObservableCollection searchUsers = new ObservableCollection();
- List arrayRes = new List();
- if (prefixes != null) arrayRes.AddRange(prefixes.Hits);
- foreach (var hit in arrayRes)
- {
- if (hit.Document is User)//如果是聯(lián)系人類型 FullTextSearchHit.Document 查詢匹配的文件
- {
- if (!searchcontacts.Contains((User)hit.Document))
- searchcontacts.Add((User)hit.Document);
- }
- }
7、刪除存儲的類的所有對象
以下是代碼片段:
- DB.DropTable(typeof(User));
- DB.Storage.Commit();//完成
8、刪除數(shù)據(jù)庫
以下是代碼片段:
- var storage = ((App)App.Current).DB.Storage;//獲取在App上定義的數(shù)據(jù)庫存儲
- storage.Close();//關(guān)閉它
- using (var store = IsolatedStorageFile.GetUserStoreForApplication())//獲取當前應(yīng)用程序使用的本地存儲文件
- {
- if (store.FileExists("PerstDemoDB.dbs"))//找到數(shù)據(jù)庫的存儲文件 perst數(shù)據(jù)庫文件是在本地存儲中的
- {
- store.DeleteFile("PerstDemoDB.dbs");//刪除這個數(shù)據(jù)庫的本地存儲文件
- }
- }
【編輯推薦】
- 微軟WP7本地數(shù)據(jù)庫之Sterling編程技巧
- WP7開發(fā)中的數(shù)據(jù)庫系統(tǒng)選擇
- 微軟WP7本機數(shù)據(jù)庫解決方案之SQLite
- 微軟WP7本地數(shù)據(jù)庫之SQLite編程技巧
- Perst嵌入式數(shù)據(jù)庫介紹