標籤:
RT/Metro商店應用如何調用SQLite資料庫使用前,要安裝:
SQLite for Windows Runtime (Windows 8.1)(一個VS外掛程式)、還有
Visual C++ Runtime Package(如:Microsoft Visual C++ 2013 Runtime Package for Windows),同時,項目產生要修改為X86或者X64,總之不能使有和AnyCPU。我這裡使用的是X86.
private async void Create() { //資料檔案儲存的位置 var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db1.sqlite"); //開啟建立資料庫和表 using (var db = new SQLite.SQLiteConnection(dbPath)) { //建立表 var result = db.CreateTable<Model.Person>(); await new MessageDialog("傳回值:" + result).ShowAsync(); } } private async void Insert() { //串連資料庫 var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db1.sqlite"); using (var db = new SQLite.SQLiteConnection(dbPath)) { //插入操作。首先聲明一個集合 ObservableCollection<Person> Collection = new ObservableCollection<Person>(); //單條插入語句 db.Insert(new Person() { FirstName = "宋興柱1", LastName = "Sindrol" }); Collection.Add(new Person() { FirstName = "宋興柱2", LastName = "Sindrol1" }); Collection.Add(new Person() { FirstName = "宋興柱3", LastName = "Sindrol2" }); //多條插入集合 var result = db.InsertAll(Collection); await new MessageDialog("傳回值:" + result).ShowAsync(); } } private async void Update() { //更新語句 var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db1.sqlite"); using (var db = new SQLite.SQLiteConnection(dbPath)) { SQLiteCommand cmd = db.CreateCommand("update person set FirstName=‘lisa‘ where LastName=‘Sindrol‘"); var result = cmd.ExecuteNonQuery(); await new MessageDialog("傳回值:" + result).ShowAsync(); } } private async void Delete() { var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db1.sqlite"); using (var db = new SQLite.SQLiteConnection(dbPath)) { //單行刪除操作 db.Delete<Person>(1); //多行刪除 var result = db.DeleteAll<Person>(); await new MessageDialog("傳回值:" + result).ShowAsync(); } } private async void Select() { var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db1.sqlite"); using (var db = new SQLite.SQLiteConnection(dbPath)) { //查詢所有資料繫結到UI List<object> list = db.Query(new TableMapping(typeof(Person)), "select * from Person"); gridView.ItemsSource = list; } }
Person類如所示:
class Person { [SQLite.AutoIncrement, SQLite.PrimaryKey] public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
資料庫:
RT/Metro商店應用如何調用SQLite資料庫