Windows Phone开发(48):不可或缺的本地数据库

来源:互联网 发布:个人网络循环贷款 编辑:程序博客网 时间:2024/05/20 01:36

也许WP7的时候,是想着让云服务露两手,故似乎并不支持本地数据库,所有数据都上传上“云”数据库中。不过呢,在SDK 7.1后,又加进了本地数据库功能。

这个本地数据库的操作,与我们平常在WindowsForm或WPF项目中所使用数据库的情况有些不一样:一者没有图形化的设计器;二来不使用SQL语句。

那么,你一定会问:“那用什么来处理与数据库的交互?”

不知道各位.NET基础学得怎么样,如果你的基础比较扎实,一提到不使用SQL语句也能操作数据库,你大脑里肯定闪出一道亮光,你一定想到了。

对啊,就是那个很有趣很好玩的LINQ,是啊,LINQ是什么,估计不用我介绍了,新发明,当然也不新了,呵呵。

那么,我们应该还记得Linq to SQL这个东西,各位在其他项目中一定玩得很熟,怎么玩的呢?我来帮大家回忆一下吧。在VS里面打开一个数据库,新建一个LINQ to SQL类,然后把数据库中的表拖到设计窗口,实际上,就生成了一个个实体类了。如何?有印象吧,如果没有,对不起,回去复习。

DataContext类会被翻译为“数据上下文”,读起来是不是有些莫名其妙,不管它,你就把它当成是数据库的一个代理,就好像看到它就看到数据库一样;就好比某人的照片一样,看到照片你就想起她。

也可以理解为,一个DataContext就表示一个数据库,然后在DataContext的派生类中声明N个公共字段,类型为Table<T>,T就是你定义的实体类,一个实体类的定义就等于一个表的定义,一个DataContext的子类中定义N个Table<T>,就如同一个数据库中包含N个表一样。

 

我相信,只要对把LINQ和LINQ to SQL学得好,在WP中的本地数据库操作是绝对不需要学习新知识的。这也是.NET的一个不错的优点,高度集成统一。

 

不过呢,连接字符串就必须了解一下了,毕竟它和其他项目中的连接字符串是不同的。

重点一:数据库的路径。数据库也是一个文件,因此,它肯定也有保存路径,我们知道WP是使用独立存储的,所以,一般情况下,我们会在独立存储中创建数据库。当然,路径有两种:

(1)以appdata开头的,如appdata:/abc.sdf,意思就是应用程序安装包里面的文件(如XAP文件),这种情况不推荐,因为我们只能通过代码来创建数据库的,而添加到VS项目中的数据库文件一般是从独立存储区中提取的,但我们不太必要这样做。

(2)以isostore开头的,如isostore:/abc.sdf,这指示数据库位于独立存储空间中。

 

如果各位觉得这些东西太复杂,我给大家两个连接字符串,基本上可以通过,如果没有特殊需要,侈直接照抄,然后把相关的参数改一个就是了。

第一条:不带密码的:

isostore:/database.sdf

这个够简单吧,如果不带密码,就这句就够,绝对万能的,其中,database.sdf是文件名,这个嘛,你自己喜欢。

第二条:带密码的,最好要有密码

Data Source='isostore:/database.sdf';Password='123456789'

不多说,就是多了一个密码而已。

用这两条,基本可以走遍天下了。

 


没有例子是不行的,接下来,我们用实例去说明,这个实例内容不少。

在你新建WP项目后,在“解决方案资源管理器”中右击“引用”,添加引用,并找到“System.Data.Linq”。

第一部分,先写好与数据库有关的逻辑。

using System;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Ink;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using Microsoft.Phone.Data.Linq;using System.Data.Linq;using System.Data.Linq.Mapping;using System.ComponentModel;namespace MyApp{    public class MyDataContext : DataContext    {        /// <summary>        /// 连接字符串        /// </summary>        public const string ConnectionString = "Data Source='isostore:/MyDb.sdf';Password='123456'";        /// <summary>        /// 构造函数        /// </summary>        public MyDataContext() : base(ConnectionString) { }        public Table<Students> Students;    }    [Table]    public class Students : INotifyPropertyChanged, INotifyPropertyChanging    {        string _stuNo;        /// <summary>        /// 学号        /// </summary>        [Column(CanBeNull = false, IsPrimaryKey = true)]        public string StuNo        {            get            {                return this._stuNo;            }            set            {                if (_stuNo != value)                {                    OnPropertyChanging(new PropertyChangingEventArgs("StuNo"));                    this._stuNo = value;                    OnPropertyChanged(new PropertyChangedEventArgs("StuNo"));                }            }        }        string _name;        /// <summary>        /// 姓名        /// </summary>        [Column]        public string Name        {            get            {                return this._name;            }            set            {                if (_name != value)                {                    OnPropertyChanging(new PropertyChangingEventArgs("Name"));                    _name = value;                    OnPropertyChanged(new PropertyChangedEventArgs("Name"));                }            }        }        string _email;        /// <summary>        /// 电邮        /// </summary>        [Column]        public string Email        {            get            {                return this._email;            }            set            {                if (_email != value)                {                    OnPropertyChanging(new PropertyChangingEventArgs("Email"));                    _email = value;                    OnPropertyChanged(new PropertyChangedEventArgs("Email"));                }            }        }        public event PropertyChangingEventHandler PropertyChanging;        public event PropertyChangedEventHandler PropertyChanged;        protected void OnPropertyChanging(PropertyChangingEventArgs e)        {            if (PropertyChanging != null)            {                PropertyChanging(this, e);            }        }        protected void OnPropertyChanged(PropertyChangedEventArgs e)        {            if (PropertyChanged != null)            {                PropertyChanged(this, e);            }        }    }}


注意,实体类必须要实现INotifyPropertyChanged接口,最好连同INotifyPropertyChanging接口,这样可以改善性能。记住了,一定要实现这两个接口,而且要触发PropertyChanging和PropertyChanged事件,不然你提交到数据库是不能更新数据的。

这个我想不难懂,因为在WPF里面也是这样的,除非你把实体类的属性都定义为依赖项属性,但最好不要这样,依赖项属性虽然节约内存,但是因为它需要进行全局注册,有可能会拖延应用程序的启动时间。

 


第二部分,创建数据库。

独立存储本来是没有数据库的,所以,在第一次使用应用程序时,必须先创建数据库,你说,在什么时候创建呢?想来想去,还是在应用程序类的构造函数中判断数据库是否存在,如果不存在,就创建。

            #region 创建数据库            using (MyDataContext dc = new MyDataContext())            {                if (dc.DatabaseExists() == false)                {                    dc.CreateDatabase();                }            }            #endregion

以上代码是写在App类的构造函数中。

 

 

第三部分,应用程序页面。

我们做一个简单的“学员信息登记系统”,道先应用程序运行时打开主页,主页上显示已经添加到数据库中的学员信息,在列表上每条记录都有两个操作按钮:“编辑”按钮点击后会跳到修改页,允许用户修改学员信息;“删除”按钮不用我说了,一去不复返。

主页一下方的应用程序栏中有两个按钮,“刷新”和“新增”,刷新不用解释,新增就是跳到新增页面,输入新学员信息,然后保存。

先看看几个效果图吧。

 

 

 

 

 

 

首先,我们要用到一个图标,不用自己做,SDK自带了一堆,在这里可以找到C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Icons\dark,看到喜欢的添加到项目中即可,生成操作设为“内容”,“如果较新则复制”。

 

主页:MainPage.xaml

<phone:PhoneApplicationPage     x:Class="MyApp.MainPage"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="696"    FontFamily="{StaticResource PhoneFontFamilyNormal}"    FontSize="{StaticResource PhoneFontSizeNormal}"    Foreground="{StaticResource PhoneForegroundBrush}"    SupportedOrientations="Portrait" Orientation="Portrait"    shell:SystemTray.IsVisible="True">    <!--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="学员列表" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>        </StackPanel>        <!--ContentPanel - 在此处放置其他内容-->        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">            <ListBox Name="stuList" HorizontalContentAlignment="Center">                <ListBox.ItemTemplate>                    <DataTemplate>                        <Grid Margin="2,10,2,2">                            <Grid.RowDefinitions>                                <RowDefinition Height="auto"/>                                <RowDefinition Height="auto"/>                                <RowDefinition Height="auto"/>                            </Grid.RowDefinitions>                            <Grid.ColumnDefinitions>                                <ColumnDefinition Width="Auto" />                                <ColumnDefinition />                                <ColumnDefinition Width="Auto" />                            </Grid.ColumnDefinitions>                            <TextBlock Grid.Column="0"                                       Grid.Row="0"                                       Text="学号:"/>                            <TextBlock Grid.Column="0"                                       Grid.Row="1"                                       Text="姓名:"/>                            <TextBlock Grid.Column="0"                                       Grid.Row="2"                                       Text="电邮:"/>                            <TextBlock Grid.Column="1"                                       Grid.Row="0"                                       Text="{Binding StuNo}"/>                            <TextBlock Grid.Column="1"                                       Grid.Row="1"                                       Text="{Binding Name}"/>                            <TextBlock Grid.Column="1"                                       Grid.Row="2"                                       Text="{Binding Email}"/>                            <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="1" Grid.RowSpan="2">                                <Button BorderThickness="0"                                        Tag="{Binding StuNo}"                                        Click="OnDataEdit"                                        Margin="-5">                                    <Button.Content>                                        <Image Stretch="Uniform" Source="appbar.edit.rest.png"/>                                    </Button.Content>                                </Button>                                <Button Tag="{Binding StuNo}"                                        Click="OnDataDelete"                                        BorderThickness="0" Margin="-5">                                    <Button.Content>                                        <Image Stretch="Uniform" Source="appbar.delete.rest.png"/>                                    </Button.Content>                                </Button>                            </StackPanel>                        </Grid>                    </DataTemplate>                </ListBox.ItemTemplate>                <ListBox.ItemContainerStyle>                    <Style TargetType="ListBoxItem">                        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>                    </Style>                </ListBox.ItemContainerStyle>            </ListBox>        </Grid>    </Grid>    <phone:PhoneApplicationPage.ApplicationBar>        <shell:ApplicationBar>            <shell:ApplicationBarIconButton Text="刷新" IconUri="appbar.refresh.rest.png" Click="onRefresh"/>            <shell:ApplicationBarIconButton Text="新增" IconUri="appbar.add.rest.png" Click="onNew"/>        </shell:ApplicationBar>    </phone:PhoneApplicationPage.ApplicationBar></phone:PhoneApplicationPage>

ListBox由于显示的项结构复杂,所以就搞了个自定义数据模板。

MainPage.xaml.cs中的代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using Microsoft.Phone.Controls;namespace MyApp{    public partial class MainPage : PhoneApplicationPage    {        // 构造函数        public MainPage()        {            InitializeComponent();        }        // 编辑        private void OnDataEdit(object sender, RoutedEventArgs e)        {            Button btn = e.OriginalSource as Button;            if (btn != null)            {                string no = btn.Tag as string;                NavigationService.Navigate(new Uri("/EditPage.xaml?sno=" + no, UriKind.Relative));            }        }        // 删除数据        private void OnDataDelete(object sender, RoutedEventArgs e)        {            Button btn = e.OriginalSource as Button;            if (btn != null)            {                string sNo = btn.Tag.ToString();                using (MyDataContext dc = new MyDataContext())                {                    Students stu = dc.Students.FirstOrDefault(s => s.StuNo == sNo);                    if (stu != null)                    {                        dc.Students.DeleteOnSubmit(stu);                        dc.SubmitChanges();                        BindList();                    }                }            }        }        private void onRefresh(object sender, EventArgs e)        {            BindList();        }        // 新增        private void onNew(object sender, EventArgs e)        {            NavigationService.Navigate(new Uri("/AddPage.xaml", UriKind.Relative));        }        /// <summary>        /// 把数据绑定到ListBox        /// </summary>        private void BindList()        {            using (MyDataContext dc = new MyDataContext())            {                var res =                    from s in dc.Students                    select s;                this.stuList.ItemsSource = res.ToList();            }        }        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)        {            base.OnNavigatedTo(e);            BindList();        }    }}


 

新增页:AddPage.xaml

<phone:PhoneApplicationPage     x:Class="MyApp.AddPage"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    FontFamily="{StaticResource PhoneFontFamilyNormal}"    FontSize="{StaticResource PhoneFontSizeNormal}"    Foreground="{StaticResource PhoneForegroundBrush}"    SupportedOrientations="Portrait" Orientation="Portrait"    mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"    shell:SystemTray.IsVisible="True">    <!--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="新增记录" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>        </StackPanel>        <!--ContentPanel - 在此处放置其他内容-->        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">            <StackPanel>                <TextBlock Text="学号:"/>                <TextBox Name="txtNo"/>                <TextBlock Text="姓名:" Margin="0,7,0,0"/>                <TextBox Name="txtName"/>                <TextBlock Margin="0,7,0,0" Text="Email:"/>                <TextBox Name="txtEmail"/>            </StackPanel>        </Grid>    </Grid>     <phone:PhoneApplicationPage.ApplicationBar>        <shell:ApplicationBar IsVisible="True">            <shell:ApplicationBarIconButton IconUri="appbar.save.rest.png" Text="保存" Click="onSave"/>            <shell:ApplicationBarIconButton IconUri="appbar.cancel.rest.png" Text="取消" Click="onCancel"/>        </shell:ApplicationBar>    </phone:PhoneApplicationPage.ApplicationBar></phone:PhoneApplicationPage>


AddPage.xaml.cs中的代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using Microsoft.Phone.Controls;namespace MyApp{    public partial class AddPage : PhoneApplicationPage    {        public AddPage()        {            InitializeComponent();        }        private void onCancel(object sender, EventArgs e)        {            //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));            if (NavigationService.CanGoBack)            {                NavigationService.GoBack();            }        }        private void onSave(object sender, EventArgs e)        {            if (txtNo.Text == "")            {                MessageBox.Show("学号不能为空。"); return;            }            if (txtName.Text == "")            {                MessageBox.Show("姓名不能为空。"); return;            }            using (MyDataContext dc = new MyDataContext())            {                if (dc.Students.Where(c=>c.StuNo == txtNo.Text).Count() > 0)                {                    MessageBox.Show("输入的学号已经存在。"); return;                }                Students stu = new Students()                {                    StuNo = txtNo.Text,                    Name = txtName.Text,                    Email = txtEmail.Text                };                dc.Students.InsertOnSubmit(stu);                dc.SubmitChanges();            }            //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));            if (NavigationService.CanGoBack)            {                NavigationService.GoBack();            }        }    }}


 

编辑页:EditPage.xaml

<phone:PhoneApplicationPage     x:Class="MyApp.EditPage"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    FontFamily="{StaticResource PhoneFontFamilyNormal}"    FontSize="{StaticResource PhoneFontSizeNormal}"    Foreground="{StaticResource PhoneForegroundBrush}"    SupportedOrientations="Portrait" Orientation="Portrait"    mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"    shell:SystemTray.IsVisible="True">    <!--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="编辑记录" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>        </StackPanel>        <!--ContentPanel - 在此处放置其他内容-->        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">            <StackPanel>                <TextBlock Text="学号:"/>                <TextBlock Name="txtNo"/>                <TextBlock Text="姓名:" Margin="0,7,0,0"/>                <TextBox Name="txtName"/>                <TextBlock Margin="0,7,0,0" Text="Email:"/>                <TextBox Name="txtEmail"/>            </StackPanel>        </Grid>    </Grid>     <phone:PhoneApplicationPage.ApplicationBar>        <shell:ApplicationBar IsVisible="True">            <shell:ApplicationBarIconButton IconUri="appbar.save.rest.png" Text="保存" Click="onSave"/>            <shell:ApplicationBarIconButton IconUri="appbar.cancel.rest.png" Text="取消" Click="onCancel"/>        </shell:ApplicationBar>    </phone:PhoneApplicationPage.ApplicationBar></phone:PhoneApplicationPage>


EditPage.xaml.cs中的代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using Microsoft.Phone.Controls;namespace MyApp{    public partial class EditPage : PhoneApplicationPage    {        public EditPage()        {            InitializeComponent();        }        private void onSave(object sender, EventArgs e)        {            if (txtName.Text == "" )            {                MessageBox.Show("姓名不能为空。"); return;            }            using (MyDataContext dc = new MyDataContext())            {                Students stu = dc.Students.FirstOrDefault(s => s.StuNo == txtNo.Text);                if (stu != null)                {                    stu.Name = txtName.Text;                    stu.Email = txtEmail.Text;                    dc.SubmitChanges();                }            }            //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));            if (NavigationService.CanGoBack)            {                NavigationService.GoBack();            }        }        private void onCancel(object sender, EventArgs e)        {            //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));            if (NavigationService.CanGoBack)            {                NavigationService.GoBack();            }        }        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)        {            base.OnNavigatedTo(e);            if (NavigationContext.QueryString.ContainsKey("sno"))            {                txtNo.Text = NavigationContext.QueryString["sno"];                using (MyDataContext dc = new MyDataContext())                {                    Students stu = dc.Students.FirstOrDefault(s => s.StuNo == txtNo.Text);                    if (stu != null)                    {                        txtName.Text = stu.Name;                        txtEmail.Text = stu.Email;                    }                }            }        }    }}


 

代码贴完了,因为实在不太好解释,而且也不算很复杂,相信各位能看得懂。

但这次的例子,代码实在有点多,所以,我会上传到“资源”中,大家去下载之后再看吧,在VS里面看代码舒服一些。


 

原创粉丝点击