Silverlight与PostgreSQL数据库的互操作(CURD完全解析)
今天将为大家介绍如何让Silverlight使用PostgreSQL作为后台数据库以及CURD操作。
准备工作
1)建立起测试项目
细节详情请见强大的DataGrid组件[2]_数据交互之ADO.NET Entity Framework——Silverlight学习笔记[10]。
2)创建测试用数据库
使用pgAdmin III,按下图所示,创建一个名为employees的PostgreSQL数据库,建立数据表名称为Employee。(注意:处理数据库对象时,PostgreSQL的PL/pgSQL语言具有区分大小写的内在属性,数据表名和列名均需使用双引号包住,引用自链接)【我用的PostgreSQL数据库版本为8.3.7,点击下载】
点击pgAdmin III工具栏上的“执行任意的SQL查询”[笔和纸的按钮],在弹出的窗口中输入如下SQL语句:
CREATE TABLE "Employee"
(
"EmployeeID" integer NOT NULL DEFAULT nextval('employees_employeeid_seq'::regclass),
"EmployeeName" character varying(45) NOT NULL,
"EmployeeAge" integer NOT NULL,
CONSTRAINT employees_pkey PRIMARY KEY ("EmployeeID")
)
WITH (OIDS=FALSE);
ALTER TABLE "Employee" OWNER TO postgres;
然后按“执行查询”按钮[绿色实心三角按钮]
3)下载Npgsql ★
为了能让.NET操作PostgreSQL数据库,请务必下载。【点击:下载】
下载解压后,将bin文件夹中的全部内容复制到服务端项目文件夹下的bin文件夹中(之后,将该文件夹包含进来),便于管理引用。
建立数据模型
EmployeeModel.cs文件(放置在服务端项目文件夹下)
using System;
using System.Collections.Generic;
using System.Linq;
namespace dataformpostgresqldb
{
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与MySQL数据库互操作的桥梁。
在Silverlight客户端应用程序文件夹下,右击References文件夹,添加名为NpgSql的命名空间(如下图)。
之后,双击EmployeesInfoWebService.asmx打开该文件,将里面的内容修改如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using Npgsql;//引入该命名空间是为了操作PostgreSQL数据库
namespace dataformpostgresqldb
{
/// <summary>
/// Summary description for EmployeesInfoWebService
/// </summary>
[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 List<EmployeeModel> GetEmployeesInfo()
{
List<EmployeeModel> returnedValue = new List<EmployeeModel>();
NpgsqlCommand Cmd = new NpgsqlCommand();
SQLExcute(@"SELECT * FROM ""Employee"" ORDER BY ""EmployeeID"" ASC", Cmd);
NpgsqlDataAdapter EmployeeAdapter = new NpgsqlDataAdapter();
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(List<EmployeeModel> employee)
{
employee.ForEach(x =>
{
string CmdText = @"INSERT INTO "
"Employee""(""EmployeeName"",""EmployeeAge"")
VALUES('" + x.EmployeeName + "'," + x.EmployeeAge.ToString() + ")";
SQLExcute(CmdText);
});
}
[WebMethod] //更新雇员信息
public void Update(List<EmployeeModel> 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(List<EmployeeModel> 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 =
"server=localhost;uid=postgres;pwd=yourpwd;database=employees";
NpgsqlConnection Conn = new NpgsqlConnection(ConnectionString);
Conn.Open();
NpgsqlCommand Cmd = new NpgsqlCommand();
Cmd.Connection = Conn;
Cmd.CommandTimeout = 15;
Cmd.CommandType = System.Data.CommandType.Text;
Cmd.CommandText = SQLCmd;
Cmd.ExecuteNonQuery();
Conn.Close();
}
//执行SQL命令文本,重载2
private void SQLExcute(string SQLCmd, NpgsqlCommand Cmd)
{
string ConnectionString =
"server=localhost;uid=postgres;pwd=yourpwd;database=employees";
NpgsqlConnection Conn = new NpgsqlConnection(ConnectionString);
Conn.Open();
Cmd.Connection = Conn;
Cmd.CommandTimeout = 15;
Cmd.CommandType = System.Data.CommandType.Text;
Cmd.CommandText = SQLCmd;
Cmd.ExecuteNonQuery();
}
}
}
在Silverlight客户端应用程序文件夹下,右击References文件夹,选择菜单选项Add Service Reference...。如下图所示,引入刚才我们创建的Web Service(别忘了按Discover按钮进行查找)。
创建Silverlight客户端应用程序
详情参见我的[原创]Silverlight与Access数据库的互操作(CURD完全解析)。
最终效果图