Windows Phone本地数据库(SQLCE):10、创建数据库(翻译) (转)
时间:2022-03-10 17:57
这是“windows phone mango本地数据库(sqlce)”系列短片文章的第十篇。 为了让你开始在Windows Phone Mango中使用数据库,这一系列短片文章将覆盖所有你需要知道的知识点。我将谈谈创建一个windows phone mango本地数据库。
1、创建数据库
在你创建了DataContext对象后,你可以创建本地数据库并且执行一些额外的数据库操作。
注释:数据库被创造后,它是自动分配的一个版本。为了确定数据库版本,使用DatabaseSchemaUpdater 类。
参考:你可以看一看MSDN文档:
示例:
注释: 在开始使用本地数据库之前,它一定要存在。这就是为什么在下面的代码中我我们要检查数据库是否存在,如果不存在,我们要使用DataContext的CreateDatabase()方法创建数据库。(注意连接字符串要正确)
1 private const string ConnectionString = @"isostore:/CountryDB.sdf"; 2 3 public MainPage() 4 { 5 InitializeComponent(); 6 7 using (CountryDataContext context = new CountryDataContext(ConnectionString)) 8 { 9 10 if (!context.DatabaseExists()) 11 { 12 // create database if it does not exist 13 context.CreateDatabase(); 14 } 15 } 16 }
1 public class CountryDataContext : DataContext 2 { 3 public CountryDataContext(string connectionString) 4 : base(connectionString) 5 { 6 } 7 8 public Table<Country> Countries 9 { 10 get 11 { 12 return this.GetTable<Country>(); 13 } 14 } 15 16 public Table<City> Cities 17 { 18 get 19 { 20 return this.GetTable<City>(); 21 } 22 } 23 }
重要的注释:上面的示例中,当调用CreateDatabase()时,数据库会在IsolatedStorage中创建(注意连接字符串中的isostore 关键字)。在widows phone 7中所有的应用程序都是相互“隔离”的,这意味着一个程序只能访问它自己的IsolatedStorage,即一个数据库只能被一个应用程序使用而不能在多个应用程序间共享。
这篇文章我谈论了在windows phone mango创建本地数据库。请继续关注接下来的文章。
Windows Phone本地数据库(SQLCE):10、创建数据库(翻译) (转),布布扣,bubuko.com