[原创]Silverlight与Access数据库的互操作(CURD完全解析)
Silverlight 与 SQL Server 或 SQL Server Express 的互操作,已成为我们常见的开发 Siverlight 应用程序的一种模式。可是在开发一些小型应用程序时,我们就需要使用一些小巧的轻量级的数据库,比如 Access 数据库。由于 Visual Studio 中并没有直接提供 Sil
Silverlight与SQL Server或SQL Server Express的互操作,已成为我们常见的开发Siverlight应用程序的一种模式。可是在开发一些小型应用程序时,我们就需要使用一些小巧的轻量级的数据库,比如Access数据库。由于Visual Studio中并没有直接提供Silverlight与Access互操作的系列方法。于是本文就将为大家介绍如何让Silverlight使用Access作为后台数据库。
准备工作
1)建立起测试项目
细节详情请见强大的DataGrid组件[2]_数据交互之ADO.NET Entity Framework——Silverlight学习笔记[10]。
2)创建测试用数据库
如下图所示,创建一个名为Employees.mdb的Access数据库,建立数据表名称为Employee。将该数据库置于作为服务端的项目文件夹下的App_Data文件夹中,便于操作管理。
建立数据模型
EmployeeModel.cs文件(放置在服务端项目文件夹下)
using System;
using System.Collections.Generic;
using System.Linq;
namespace datagridnaccessdb
{
public class EmployeeModel
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public int EmployeeAge { get; set; }
}
}
建立服务端Web Service★
右击服务端项目文件夹,选择Add->New Item....,按下图所示建立一个名为EmployeesInfoWebService.asmx的Web Service,作为Silverlight与Access数据库互操作的桥梁。
创建完毕后,双击EmployeesInfoWebService.asmx打开该文件。将里面的内容修改如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.OleDb;//引入该命名空间为了操作Access数据库
using System.Data;
namespace datagridnaccessdb
{
///
/// Summary description for EmployeesInfoWebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class EmployeesInfoWebService : System.Web.Services.WebService
{
[WebMethod]//获取雇员信息
public ListEmployeeModel> GetEmployeesInfo()
{
ListEmployeeModel> returnedValue = new ListEmployeeModel>();
OleDbCommand Cmd = new OleDbCommand();
SQLExcute("SELECT * FROM Employee", Cmd);
OleDbDataAdapter EmployeeAdapter = new OleDbDataAdapter();
EmployeeAdapter.SelectCommand = Cmd;
DataSet EmployeeDataSet = new DataSet();
EmployeeAdapter.Fill(EmployeeDataSet);
foreach (DataRow dr in EmployeeDataSet.Tables[0].Rows)
{
EmployeeModel tmp = new EmployeeModel();
tmp.EmployeeID = Convert.ToInt32(dr[0]);
tmp.EmployeeName = Convert.ToString(dr[1]);
tmp.EmployeeAge = Convert.ToInt32(dr[2]);
returnedValue.Add(tmp);
}
return returnedValue;
}
[WebMethod] //添加雇员信息
public void Insert(ListEmployeeModel> employee)
{
employee.ForEach( x =>
{
string CmdText = "INSERT INTO Employee(EmployeeName,EmployeeAge) VALUES('"+x.EmployeeName+"',"+x.EmployeeAge.ToString()+")";
SQLExcute(CmdText);
});
}
[WebMethod] //更新雇员信息
public void Update(ListEmployeeModel> employee)
{
employee.ForEach(x =>
{
string CmdText = "UPDATE Employee SET EmployeeName='"+x.EmployeeName+"',EmployeeAge="+x.EmployeeAge.ToString();
CmdText += " WHERE EmployeeID="+x.EmployeeID.ToString();
SQLExcute(CmdText);
});
}
[WebMethod] //删除雇员信息
public void Delete(ListEmployeeModel> employee)
{
employee.ForEach(x =>
{
string CmdText = "DELETE FROM Employee WHERE EmployeeID="+x.EmployeeID.ToString();
SQLExcute(CmdText);
});
}
//执行SQL命令文本,重载1
private void SQLExcute(string SQLCmd)
{
string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath(@"App_Data\Employees.mdb;");
Conn.Open();
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection =
Cmd.CommandTimeout = 15;
Cmd.CommandType = CommandType.Text;
Cmd.CommandText = SQLCmd;
Cmd.ExecuteNonQuery();
Conn.Close();
}
//执行SQL命令文本,重载2
private void SQLExcute(string SQLCmd,OleDbCommand Cmd)
{
string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath(@"App_Data\Employees.mdb;");
Conn.Open();
Cmd.Connection =
Cmd.CommandTimeout = 15;
Cmd.CommandType = CommandType.Text;
Cmd.CommandText = SQLCmd;
Cmd.ExecuteNonQuery();
}
}
}
之后,在Silverlight客户端应用程序文件夹下,右击References文件夹,选择菜单选项Add Service Reference...。如下图所示,引入刚才我们创建的Web Service(别忘了按Discover按钮进行查找)。
创建Silverlight客户端应用程序
MainPage.xaml文件
UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" xmlns:dataFormToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit" x:Class="SilverlightClient.MainPage"
d:DesignWidth="320" d:DesignHeight="240">
Grid x:Name="LayoutRoot" Width="320" Height="240" Background="White">
dataFormToolkit:DataForm x:Name="dfEmployee" Margin="8,8,8,42"/>
Button x:Name="btnGetData" Height="30" Margin="143,0,100,8" VerticalAlignment="Bottom" Content="Get Data" Width="77"/>
Button x:Name="btnSaveAll" Height="30" Margin="0,0,8,8" VerticalAlignment="Bottom" Content="Save All" HorizontalAlignment="Right" Width="77"/>
TextBlock x:Name="tbResult" Height="30" HorizontalAlignment="Left" Margin="8,0,0,8" VerticalAlignment="Bottom" Width="122" TextWrapping="Wrap" FontSize="16"/>
Grid>
UserControl>
MainPage.xaml.cs文件
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 System.Xml;
using System.Xml.Linq;
using System.Windows.Browser;
using SilverlightClient.EmployeesInfoServiceReference;
namespace SilverlightClient
{
public partial class MainPage : UserControl
{
int originalNum;//记录初始时的Employee表中的数据总数
ObservableCollectionEmployeeModel> deletedID = new ObservableCollectionEmployeeModel>();//标记被删除的对象
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
this.btnGetData.Click += new RoutedEventHandler(btnGetData_Click);
this.btnSaveAll.Click += new RoutedEventHandler(btnSaveAll_Click);
this.dfEmployee.DeletingItem += new EventHandler
}
void dfEmployee_DeletingItem(object sender, System.ComponentModel.CancelEventArgs e)
{
deletedID.Add(dfEmployee.CurrentItem as EmployeeModel);//正在删除时,将被删除对象进行标记,以便传给服务端真正删除。
}
void btnSaveAll_Click(object sender, RoutedEventArgs e)
{
ListEmployeeModel> updateValues = dfEmployee.ItemsSource.CastEmployeeModel>().ToList();
ObservableCollectionEmployeeModel> returnValues = new ObservableCollectionEmployeeModel>();
if (updateValues.Count > originalNum)
{
//添加数据
for (int i = originalNum; i
{
returnValues.Add(updateValues.ToArray()[i]);
}
EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();
webClient.InsertCompleted += new EventHandler
webClient.InsertAsync(returnValues);
//必须考虑数据集中既有添加又有更新的情况
returnValues.Clear();
updateValues.ForEach(x => returnValues.Add(x));
webClient.UpdateCompleted += new EventHandler
webClient.UpdateAsync(returnValues);
}
else if (updateValues.Count
{
//删除数据
EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();
webClient.DeleteCompleted += new EventHandler
webClient.DeleteAsync(deletedID);
}
else
{
//更新数据
updateValues.ForEach(x => returnValues.Add(x));
EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();
webClient.UpdateCompleted += new EventHandler
webClient.UpdateAsync(returnValues);
}
}
void webClient_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
tbResult.Text = "更新成功!";
GetEmployees();//更新originalNum防止数据的重复插入,感谢园友紫色永恒的及时指出!
}
void webClient_DeleteCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
tbResult.Text = "删除成功!";
}
void webClient_InsertCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
tbResult.Text = "添加成功!";
}
void btnGetData_Click(object sender, RoutedEventArgs e)
{
GetEmployees();
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
GetEmployees();
}
void GetEmployees()
{
EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();
webClient.GetEmployeesInfoCompleted +=
new EventHandlerGetEmployeesInfoCompletedEventArgs>(webClient_GetEmployeesInfoCompleted);
webClient.GetEmployeesInfoAsync();
}
void webClient_GetEmployeesInfoCompleted(object sender, GetEmployeesInfoCompletedEventArgs e)
{
originalNum = e.Result.Count;//记录原始数据个数
dfEmployee.ItemsSource = e.Result;
}
}
}
最终效果图
作者:Kinglee
文章出处:Kinglee’s Blog (http://www.cnblogs.com/Kinglee/)

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

如何在 Apache 中配置 Zend?在 Apache Web 服務器中配置 Zend Framework 的步驟如下:安裝 Zend Framework 並解壓到 Web 服務器目錄中。創建 .htaccess 文件。創建 Zend 應用程序目錄並添加 index.php 文件。配置 Zend 應用程序(application.ini)。重新啟動 Apache Web 服務器。

Oracle不僅是數據庫公司,還是雲計算和ERP系統的領導者。 1.Oracle提供從數據庫到雲服務和ERP系統的全面解決方案。 2.OracleCloud挑戰AWS和Azure,提供IaaS、PaaS和SaaS服務。 3.Oracle的ERP系統如E-BusinessSuite和FusionApplications幫助企業優化運營。

MySQL適合Web應用和內容管理系統,因其開源、高性能和易用性而受歡迎。 1)與PostgreSQL相比,MySQL在簡單查詢和高並發讀操作上表現更好。 2)相較Oracle,MySQL因開源和低成本更受中小企業青睞。 3)對比MicrosoftSQLServer,MySQL更適合跨平台應用。 4)與MongoDB不同,MySQL更適用於結構化數據和事務處理。

MySQL通過表結構和SQL查詢高效管理結構化數據,並通過外鍵實現表間關係。 1.創建表時定義數據格式和類型。 2.使用外鍵建立表間關係。 3.通過索引和查詢優化提高性能。 4.定期備份和監控數據庫確保數據安全和性能優化。

vProcesserazrabotkiveb被固定,мнелостольностьстьс粹餾標д都LeavallySumballanceFriablanceFaumDoptoMatification,Čtookazalovnetakprosto,kakaožidal.posenesko

Apache服務器是強大的Web服務器軟件,充當瀏覽器與網站服務器間的橋樑。 1. 它處理HTTP請求,根據請求返回網頁內容;2. 模塊化設計允許擴展功能,例如支持SSL加密和動態網頁;3. 配置文件(如虛擬主機配置)需謹慎設置,避免安全漏洞,並需優化性能參數,例如線程數和超時時間,才能構建高性能、安全的Web應用。

Nginx 限流問題可通過以下方法解決:使用 ngx_http_limit_req_module 限制請求次數;使用 ngx_http_limit_conn_module 限制連接數;使用第三方模塊(ngx_http_limit_connections_module、ngx_http_limit_rate_module、ngx_http_access_module)實現更多限流策略;使用雲服務(Cloudflare、Google Cloud Rate Limiting、AWS WAF)進行 DD

MySQL在現實世界的應用包括基礎數據庫設計和復雜查詢優化。 1)基本用法:用於存儲和管理用戶數據,如插入、查詢、更新和刪除用戶信息。 2)高級用法:處理複雜業務邏輯,如電子商務平台的訂單和庫存管理。 3)性能優化:通過合理使用索引、分區表和查詢緩存來提升性能。
