西西软件下载最安全的下载网站、值得信赖的软件下载站!

首页编程开发其它知识 → Windows Phone 7开发中使用SQL CE数据库实例

Windows Phone 7开发中使用SQL CE数据库实例

相关软件相关文章发表评论 来源:西西整理时间:2012/12/16 20:55:23字体大小:A-A+

作者:西西点击:0次评论:0次标签: WindowsPhone

  • 类型:WM|WP7平台大小:1.5M语言:中文 评分:3.7
  • 标签:
立即下载

 在WindowsPhone中有时候我们会一些数据的存储,这个时候我们有两种选择,一种是选择存在的独立存储文件中,一种是存储在数据库中。存储在独立存储文件中,这个相信很多用都会使用,这里不作为重点,本文主要讲一下在WindowsPhone中使用数据库SQL CE。

下面开始一步一步的带领大家实现在WindowsPhone 中使用SQL CE数据库。(该示例引自WindowsPhone 7应用开发)

一、首先,我们需要创建一个EmployeeTable类,映射为数据库中的Employee表

如下:

在创建之前需要添加引用:System.Data.Linq;

同时引入命名空间:using System.Data.Linq.Mapping;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
[Table]//特性标识该类为映射为数库中的表
 //该类实现了INotifyPropertyChanged和INotifyPropertyChanging接口
   public class EmployeeTable:INotifyPropertyChanged,INotifyPropertyChanging
   {
       private int _employeeId;
       //将EmployeeID映射为表的主键,特性Column里的含义分别为:主键,自增,int型不为空,不为空等
       [Column(IsPrimaryKey = true, IsDbGenerated = true,DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
       public int EmployeeID
       {
           get
           {
               return _employeeId;
           }
           set
           {
               if (_employeeId != value)
               {
                   NotifyPropertyChanging("EmployeeID");
                   _employeeId = value;
                   NotifyPropertyChanged("EmployeeID");
               }
           }
       }
       private string _employeeName;
       [Column]//EmployeeName属性为表中EmployeeName字段
       public string EmployeeName
       {
           get
           {
               return _employeeName;
           }
           set
           {
               if (_employeeName != value)
               {
                   NotifyPropertyChanging("EmployeeName");
                   _employeeName = value;
                   NotifyPropertyChanged("EmployeeName");
               }
           }
       }
       private string _employeeDesc;
       [Column]//将EmployeeDesc属性映射为表中EmployeeDesc字段
       public string EmployeeDesc
       {
           get
           {
               return _employeeDesc;
           }
           set
           {
               if (_employeeDesc != value)
               {
                   NotifyPropertyChanging("EmployeeDesc");
                   _employeeDesc = value;
                   NotifyPropertyChanged("EmployeeDesc");
               }
           }
       }
       //定义PropertyChanged事件用来通知页面,表字段数据发生了改变
       public event PropertyChangedEventHandler PropertyChanged;
       private void NotifyPropertyChanged(string propertyName)
       {
           if (PropertyChanged != null)
           {
               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
           }
       }
       //定义PropertyChanging事件通知数据上下文表的字段数据将要发生改变
       public event PropertyChangingEventHandler PropertyChanging;
       private void NotifyPropertyChanging(string propertyname)
       {
           if (PropertyChanging != null)
           {
               PropertyChanging(this, new PropertyChangingEventArgs(propertyname));
           }
       }
   }

通过以上的这些操作,我们已经基本上完成了Employee表的创建,映射为数据库中的EmployeeTable表

二、下面我们来新建一个EmployeeDataContext.cs类文件,创建数据库的DataContent,该类继承自DataContent,在该类中定义连接字符串,如下:

首先需要引入命名空间:using system.data.Linq;

public class EmployeeDataContext:DataContext
    {
        //数据库连接字符串
        public static string DBConnectionString = "Data Source=isostore:/Employee.sdf";
        //传递数据库连接字符串到DataContext基类
        public EmployeeDataContext(string connectionString):base(connectionString)
        {
        }
        //定义员工信息表
        public Table<EmployeeTable> Employees;
    }

三、创建EmployeeCollection类,该类的主要作用为页面数据绑定的集合。如下:

    //绑定页面,进行显示用    

public class EmployeeCollection:INotifyPropertyChanged
{
    //用于通知属性的改变
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,new PropertyChangedEventArgs (propertyName));
            }
        }
        private ObservableCollection<EmployeeTable> _employeeTables;

//创建EmployeeTables属性用来绑定页面数据        

public ObservableCollection<EmployeeTable> EmployeeTables
        {
            get
            {
                return _employeeTables;
            }
            set
            {
                if (_employeeTables != value)
                {
                    _employeeTables = value;
                    NotifyPropertyChanged("EmployeeTables");
                }
            }
        }
    }

四、这样一个完整的数据库就创建完毕了,那么我们该如何使用呢?一般的情况下我们都是在程序启动的时候加载数据库,为此我们可以在App.xaml文件的Launching事件中做如下处理:

using (EmployeeDataContext db=new EmployeeDataContext(EmployeeDataContext.DBConnectionString))
           {
                if (db.DatabaseExists() == false)
                {
                    db.CreateDatabase();
                }
            }

五、下面做一个实例进行演示:

页面布局如下:

<phone:PhoneApplicationPage.Resources>
        <DataTemplate x:Key="listitem">
            <Grid HorizontalAlignment="Stretch" Width="440">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="50"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="100"/>
                 </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding EmployeeName}" FontSize="{StaticResource PhoneFontSizeLarge}" Grid.Column="1" <BR>VerticalAlignment="Center"/>
                <Button Grid.Column="2" Click="deleteButton_Click" x:Name="deleteButton" BorderThickness="0" Margin="0" Content="删除" ></Button>
                <Button Grid.Column="1" x:Name="editButton" Click="editButton_Click"BorderThickness="0" Margin="209,0,81,0" Content="编辑" <BR>Grid.ColumnSpan="2"></Button>
            </Grid>
        </DataTemplate>
    </phone:PhoneApplicationPage.Resources>
    <!--LayoutRoot 是包含所有页面内容的根网格-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <!--TitlePanel 包含应用程序的名称和页标题-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="我的应用程序" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="EmployeeShow" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>
        <!--ContentPanel - 在此处放置其他内容-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock FontSize="24" Name="textBlock1" Text="员工名字:
                       " Margin="12,22,330,544" />
            <TextBlock FontSize="24" Margin="12,93,330,473" Name="textBlock2" Text="简介:" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="132,6,0,0" Name="txtname" Text=""
                    VerticalAlignment="Top" Width="281" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="132,78,0,0" Name="txtdesc" Text=""
                    VerticalAlignment="Top" Width="281" />
            <Button Content="保存" Height="72" HorizontalAlignment="Left" Margin="243,150,0,0" Name="button2"
                    VerticalAlignment="Top" Width="160" Click="button2_Click" />
            <ListBox Height="293" HorizontalAlignment="Left" Margin="-12,228,0,0" Name="listBox1" VerticalAlignment="Top"
                    Width="460" ItemTemplate="{StaticResource listitem}" />
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>

.cs页的处理代码如下:

public partial class EmployeeShow : PhoneApplicationPage
    {
        //创建DataContext用于操作独立的数据库
        private EmployeeDataContext employeeDB;
        private EmployeeCollection employeeCol = new EmployeeCollection();

      

  public EmployeeShow()
        {
            InitializeComponent();
    //创建EmployeeDataContext实例        
    employeeDB = new EmployeeDataContext(EmployeeDataContext.DBConnectionString);
            var employeeInDB = from EmployeeTable employee in employeeDB.Employees
                               select employee;
 //为页面创建数据绑定源            
employeeCol.EmployeeTables = new System.Collections.ObjectModel.ObservableCollection<EmployeeTable>(employeeInDB);
            listBox1.ItemsSource = employeeCol.EmployeeTables;
        }

        //删除信息        

private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button != null)
            {
                EmployeeTable edelete = button.DataContext as EmployeeTable;
                //
                employeeCol.EmployeeTables.Remove(edelete);
                employeeDB.Employees.DeleteOnSubmit(edelete);
                employeeDB.SubmitChanges();
            }
        }

     //保存信息        

private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (txtname.Text != "" && txtdesc.Text != "")
            {
                //编辑状态
                if (State.Count > 0 && State["employee"] != null)
                {
                    EmployeeTable employee = (EmployeeTable)State["employee"];
                    employee.EmployeeName = txtname.Text;
                    employee.EmployeeDesc = txtdesc.Text;
                    employeeDB.SubmitChanges();
                    employeeCol.EmployeeTables.Add(employee);
                    State["employee"] = null;
                }
                Else//添加新的信息
                {
                    EmployeeTable newEmployee = new EmployeeTable
                    {
                        EmployeeName = txtname.Text,
                        EmployeeDesc = txtdesc.Text
                    };
                    employeeCol.EmployeeTables.Add(newEmployee);
                    employeeDB.Employees.InsertOnSubmit(newEmployee);
                    employeeDB.SubmitChanges();
                    txtname.Text = "";
                    txtdesc.Text = "";
                }
                listBox1.ItemsSource = employeeCol.EmployeeTables;
            }
            else
            {
                MessageBox.Show("姓名和简介不能为空!");
            }
        }

        //编辑信息     

private void editButton_Click(object sender, RoutedEventArgs e)
     {
         var button = sender as Button;
         if (button != null)
         {
             EmployeeTable eedit = button.DataContext as EmployeeTable;
             txtname.Text = eedit.EmployeeName;
             txtdesc.Text = eedit.EmployeeDesc;
             State["employee"] = eedit;
             employeeCol.EmployeeTables.Remove(eedit);      
         }
     }
 }

效果如图:

好了,到这里我们已经基本上实现了在WindowsPhone手机中使用SQLCE数据库了,希望可以对朋友们有所帮助。

    金山手机助手
    (130)金山手机助手
    金山手机助手是智能手机的资源获取平台。金山手机控帮助手机使用者用最省流量最快捷最方便最安全的方式获取网络资源,只需通过数据线的方式将手机连接至,便可以通过金山手机助手下载海量应用,电子书视频音乐图片应有尽有,游戏应用软件一应俱全。还可以通过它进行应用管理任务管理,图片视频音乐等导入导出等等。功能特色金山手机控除了自有软件游戏宝库,还提供超过万款手机资源,不花手机流量,一键下载安装。金山手机控提供的...更多>>
    91手机助手
    (17)91手机助手
    手机助手拥有无比强大的功能,可以方便快捷的管理和安装手机应用,清理无效文件,备份通讯录,收发短信等。使用助手安卓版,通过电脑即可轻松管理智能手机,下载海量的手机游戏手机软件手机音乐手机铃声手机壁纸手机主题手机电影等各种手机应用,大大节省手机流量。...更多>>

    相关评论

    阅读本文后您有什么感想? 已有人给出评价!

    • 8 喜欢喜欢
    • 3 顶
    • 1 难过难过
    • 5 囧
    • 3 围观围观
    • 2 无聊无聊

    热门评论

    最新评论

    发表评论 查看所有评论(0)

    昵称:
    表情: 高兴 可 汗 我不要 害羞 好 下下下 送花 屎 亲亲
    字数: 0/500 (您的评论需要经过审核才能显示)
    推荐文章

    没有数据