WinPhone開發(fā)數據庫相關操作總結
1.首先來說下wp對.sqlite數據庫的操作支持,從google,百度,codeplex..等等網站找尋到以下方式;
(1)最古老的要數引用第三方Community.CsharpSqlite.WP.dll程序集來使用的(注意:如果你要操作現有存在的.sqlite數據庫,而不是自己從頭開始創(chuàng)建數據表,添加數據...等,那么你需要在codeplex網站上找到這個源碼,進行相應的修改,這樣才能夠支持使用,不然會碰到很郁悶的"無法打開數據庫連接.."之類的錯誤)
(2)第二種跟***種有所類似,不過它的封裝有所不同C#-SQLiteWP7.Preview1.Release,這個也在Codeplex上面,代碼使用跟***種類似,不過里面的方法有返回DataReader之類的對象,這樣方便我們做相應數據讀取操作,雖然數據庫也是copy到獨立存儲根目錄下的,不過這里的連接字符串有所不同,格式如下:
"Version=數據庫版本號,uri=file:你的數據庫完整名稱"
簡單的Code操作流程:
- using (SqliteConnection conn = new SqliteConnection("Version=3,uri=file:test.db"))
- {
- conn.Open();
- using (SqliteCommand cmd = conn.CreateCommand())
- {
- cmd.CommandText = "sql語句";
- cmd.ExecuteNonQuery();
- cmd.Transaction = conn.BeginTransaction();
- //sql語句加入參數
- cmd.CommandText = "INSERT INTO test(col, col2, col3, col4, col5) VALUES(@col, @col2, @col3, @col4, @col5);SELECT last_insert_rowid();";
- cmd.Parameters.Add("@col", null);
- cmd.Parameters.Add("@col2", null);
- cmd.Parameters.Add("@col3", null);
- cmd.Parameters.Add("@col4", null);
- cmd.Parameters.Add("@col5", null);
- cmd.Transaction.Commit();
- cmd.Transaction = null;
如果自己不想改Community.CsharpSqlite.WP這個源碼的話,那就在網上找找Vici.CoolStorage.WP7和Vici.Core.WP7這兩個程序集,個人感覺這個方式,代碼操作簡單,性能較***種好些許;
- //注意:先往項目添加Vici.CoolStorage.WP7.dll和Vici.Core.WP7.dll
- string fn = "MNSECRET.DB";//您的數據庫名稱,注意放在項目根目錄下,且設置生成操作為Resource,不復制
- Assembly assem = Assembly.GetExecutingAssembly();
- string assemeblyName=assem.FullName.Substring(0, assem.FullName.IndexOf(','));
- Uri dbURi= new Uri("/" + assemeblyName + ";component/" + fn,
- UriKind.Relative);
- //程序***次運行把SQLite數據庫Copy到本地存儲
- StreamResourceInfo sr = Application.GetResourceStream(dbURi);
- IsolatedStorageFile iStorage = IsolatedStorageFile.GetUserStoreForApplication();
- if (!iStorage.FileExists(fn))
- {
- using (var outputStream = iStorage.OpenFile(fn, FileMode.CreateNew))
- {
- byte[] buffer = new byte[10000];
- for (; ; )
- {
- int read = sr.Stream.Read(buffer, 0, buffer.Length);
- if (read <= 0)
- break;
- outputStream.Write(buffer, 0, read);
- }
- }
- }
- //連接數據庫
- CSConfig.SetDB(fn);
- //數據操作
- CSGenericRecordList cslis = CSDatabase.RunQuery("SELECT* FROM CITY");//可以理解為返回一個表格
- foreach (CSGenericRecord cs in cslis)
- {
- //取表中的每一行數據
- string result= cs["數據表字段名"].ToString();
- }
本文鏈接:http://wp.662p.com/thread-8290-1-1.html