zoukankan      html  css  js  c++  java
  • Windows Phone本地数据库(SQLCE):12、插入数据(翻译)

    这是“windows phone mango本地数据库(sqlce)”系列短片文章的第十二篇。 为了让你开始在Windows Phone Mango中使用数据库,这一系列短片文章将覆盖所有你需要知道的知识点。我将谈谈在windows phone mango本地数据库里怎么插入数据。

       插入数据到数据库是一个两个步骤的过程。首先使用InsertOnSubmit 方法添加一个对象到DataContext,然后调用DataContext的SubmitChanges 方法来将保存数据作为数据库中的行。
    注释:直到SubmitChanges调用后数据才真正保存到数据库中。

    1、怎么插入数据

        在开始之前,假设我们有下面两张表的数据库结构:Country和City

    复制代码
     1 [Table]
     2  public class Country
     3  {
     4   //...
     5  }
     6   
     7   
     8  [Table]
     9  public class City
    10  {
    11      //...
    12  }
    复制代码

    DataContext如下所示:

    复制代码
     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  }
    复制代码

       在下面的代码示例中,我们将演示这个过程,解释上面的被装箱以及插入两个新的关系对象(city和country)到数据库中。首先,我们创建一个新的country实例,然后添加到context中(使用InsertOnSubmit 方法)。接下来,我们创建一个city实例,分配到我们刚创建的country实例,然后添加到context中。最后,我们调用SubmitChanges 方法保存这些变化到数据库中。

    复制代码
     1 private void AddCity()
     2  {
     3      using (CountryDataContext context = new CountryDataContext(ConnectionString))
     4      {
     5          // create a new country instance
     6          Country country = new Country();
     7          country.Name = "Spain";
     8          // add the new country to the context
     9          context.Countries.InsertOnSubmit(country);
    10   
    11          // create a new city instance
    12          City city = new City();
    13          city.Name = "Barcelona";
    14          // assing country
    15          city.Country = country;
    16          // add the new city to the context
    17          context.Cities.InsertOnSubmit(city);
    18   
    19          // save changes to the database
    20          context.SubmitChanges();
    21      }
    22  }
    复制代码

        这篇文章我谈论了在windows phone mango本地数据库插入数据。请继续关注接下来的文章。

  • 相关阅读:
    forward redirect 区别
    request response 区别
    Java集合 初步了解
    通过session统计当前在线人数
    Session保存用户名到Session域对象中
    Cookie获取用户的访问记录
    表单中有关于爱好的多选框, 篮球,足球,游泳,跑步, 再有一个多选框,代表全选
    jQuery常用子元素过滤选择器
    jQuery常用属性过滤选择器
    jQuery常见可见性过滤选择器
  • 原文地址:https://www.cnblogs.com/zgqys1980/p/3838291.html
Copyright © 2011-2022 走看看