西西軟件下載最安全的下載網(wǎng)站、值得信賴的軟件下載站!

首頁編程開發(fā)其它知識 → Windows Phone 7開發(fā)中使用SQL CE數(shù)據(jù)庫實例

Windows Phone 7開發(fā)中使用SQL CE數(shù)據(jù)庫實例

相關軟件相關文章發(fā)表評論 來源:西西整理時間:2012/12/16 20:55:23字體大。A-A+

作者:西西點擊:0次評論:0次標簽: WindowsPhone

  • 類型:WM|WP7平臺大小:1.5M語言:中文 評分:3.7
  • 標簽:
立即下載

 在WindowsPhone中有時候我們會一些數(shù)據(jù)的存儲,這個時候我們有兩種選擇,一種是選擇存在的獨立存儲文件中,一種是存儲在數(shù)據(jù)庫中。存儲在獨立存儲文件中,這個相信很多用都會使用,這里不作為重點,本文主要講一下在WindowsPhone中使用數(shù)據(jù)庫SQL CE。

下面開始一步一步的帶領大家實現(xiàn)在WindowsPhone 中使用SQL CE數(shù)據(jù)庫。(該示例引自WindowsPhone 7應用開發(fā))

一、首先,我們需要創(chuàng)建一個EmployeeTable類,映射為數(shù)據(jù)庫中的Employee表

如下:

在創(chuàng)建之前需要添加引用: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]//特性標識該類為映射為數(shù)庫中的表
 //該類實現(xiàn)了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事件用來通知頁面,表字段數(shù)據(jù)發(fā)生了改變
       public event PropertyChangedEventHandler PropertyChanged;
       private void NotifyPropertyChanged(string propertyName)
       {
           if (PropertyChanged != null)
           {
               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
           }
       }
       //定義PropertyChanging事件通知數(shù)據(jù)上下文表的字段數(shù)據(jù)將要發(fā)生改變
       public event PropertyChangingEventHandler PropertyChanging;
       private void NotifyPropertyChanging(string propertyname)
       {
           if (PropertyChanging != null)
           {
               PropertyChanging(this, new PropertyChangingEventArgs(propertyname));
           }
       }
   }

通過以上的這些操作,我們已經(jīng)基本上完成了Employee表的創(chuàng)建,映射為數(shù)據(jù)庫中的EmployeeTable表

二、下面我們來新建一個EmployeeDataContext.cs類文件,創(chuàng)建數(shù)據(jù)庫的DataContent,該類繼承自DataContent,在該類中定義連接字符串,如下:

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

public class EmployeeDataContext:DataContext
    {
        //數(shù)據(jù)庫連接字符串
        public static string DBConnectionString = "Data Source=isostore:/Employee.sdf";
        //傳遞數(shù)據(jù)庫連接字符串到DataContext基類
        public EmployeeDataContext(string connectionString):base(connectionString)
        {
        }
        //定義員工信息表
        public Table<EmployeeTable> Employees;
    }

三、創(chuàng)建EmployeeCollection類,該類的主要作用為頁面數(shù)據(jù)綁定的集合。如下:

    //綁定頁面,進行顯示用    

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;

//創(chuàng)建EmployeeTables屬性用來綁定頁面數(shù)據(jù)        

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

四、這樣一個完整的數(shù)據(jù)庫就創(chuàng)建完畢了,那么我們該如何使用呢?一般的情況下我們都是在程序啟動的時候加載數(shù)據(jù)庫,為此我們可以在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 是包含所有頁面內(nèi)容的根網(wǎng)格-->
    <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 - 在此處放置其他內(nèi)容-->
        <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
    {
        //創(chuàng)建DataContext用于操作獨立的數(shù)據(jù)庫
        private EmployeeDataContext employeeDB;
        private EmployeeCollection employeeCol = new EmployeeCollection();

      

  public EmployeeShow()
        {
            InitializeComponent();
    //創(chuàng)建EmployeeDataContext實例        
    employeeDB = new EmployeeDataContext(EmployeeDataContext.DBConnectionString);
            var employeeInDB = from EmployeeTable employee in employeeDB.Employees
                               select employee;
 //為頁面創(chuàng)建數(shù)據(jù)綁定源            
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 != "")
            {
                //編輯狀態(tài)
                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);      
         }
     }
 }

效果如圖:

好了,到這里我們已經(jīng)基本上實現(xiàn)了在WindowsPhone手機中使用SQLCE數(shù)據(jù)庫了,希望可以對朋友們有所幫助。

    金山手機助手
    (130)金山手機助手
    金山手機助手是智能手機的資源獲取平臺。金山手機控幫助手機使用者用最省流量最快捷最方便最安全的方式獲取網(wǎng)絡資源,只需通過數(shù)據(jù)線的方式將手機連接至,便可以通過金山手機助手下載海量應用,電子書視頻音樂圖片應有盡有,游戲應用軟件一應俱全。還可以通過它進行應用管理任務管理,圖片視頻音樂等導入導出等等。功能特色金山手機控除了自有軟件游戲?qū)殠,還提供超過萬款手機資源,不花手機流量,一鍵下載安裝。金山手機控提供的...更多>>
    91手機助手
    (17)91手機助手
    手機助手擁有無比強大的功能,可以方便快捷的管理和安裝手機應用,清理無效文件,備份通訊錄,收發(fā)短信等。使用助手安卓版,通過電腦即可輕松管理智能手機,下載海量的手機游戲手機軟件手機音樂手機鈴聲手機壁紙手機主題手機電影等各種手機應用,大大節(jié)省手機流量。...更多>>

    相關評論

    閱讀本文后您有什么感想? 已有人給出評價!

    • 8 喜歡喜歡
    • 3 頂
    • 1 難過難過
    • 5 囧
    • 3 圍觀圍觀
    • 2 無聊無聊

    熱門評論

    最新評論

    發(fā)表評論 查看所有評論(0)

    昵稱:
    表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
    字數(shù): 0/500 (您的評論需要經(jīng)過審核才能顯示)
    推薦文章

    沒有數(shù)據(jù)