首页 运维 正文
几步走,教你创建简单访问数据库方法

 2022-10-23    401  

本文将建立一个最简单的WCF RIA Services访问数据库的实例,附带有数据库文件,可以在SQL Server中附加数据库,在本文中并没有采用ADO.NET实体数据模型绑定数据库,而是单独写一个类来连接数据库查询数据表并返回值,下面我们看详细步骤。

第一步:首先我们打开VS2010,新建一个Silverlight应用程序项目SLGetDataFromWCFRIA。

第二步:点击确定之后,在弹出的“新建Silverlight应用程序”窗口中,选中“启用 WCF RIA 服务”复选框然后确定。

第三步:在创建好的项目中,鼠标右键点击“SLGetDataFromWCFRIA.Web”项目,然后“添加”–>“新建项”–>“WCF服务”,命名为SLWCFRIA.svc。

第四步:在上一步生成的ISLWCFRIA.cs文件中,我们可以定义相关的通信的契约,在本实例中我们定义一个string GetData()契约。

第五步:在SLWCFRIA.svc.cs文件中我们实现这个契约函数,代码如下:

usingSystem; 
usingSystem.Collections.Generic; 
usingSystem.Linq; 
usingSystem.Runtime.Serialization; 
usingSystem.ServiceModel; 
usingSystem.Text; 
usingSystem.Data; 
usingSystem.Data.SqlClient; 
namespaceSLGetDataFromWCFRIA.Web{ 
//注意:使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc和配置文件中的类名“SLWCFRIA”。 
publicclassSLWCFRIA:ISLWCFRIA 
{ 
publicvoidDoWork() 
{ 
} 
publicstringGetData() 
{ 
DataSetds=DB.Getdata("select*fromuserinfo"); 
returnds.GetXml(); 
} 
} 
} 

#p#

第七步:我们在SQL SERVER2008中创建一个示例数据库名为SLRiaTest。在这个数据库里面新增一个UserInfo表,在里面添加字段如下:

第八步:编写一个类,来连接SLRiaTest数据库,获取DataSet数据集。

DB.cs数据库访问类 
///<summary>
///DB的摘要说明 
///</summary>
publicclassDB 
{ 
privatestaticIsolationLevelm_isoLevel=IsolationLevel.ReadUncommitted; 
privatestaticstringconnStr=string.Empty; 
privateDB() 
{ 
} 
#regionDB2AccessFunctions 
staticpublicIsolationLevelIsolationLevel 
{ 
get 
{ 
returnm_isoLevel; 
} 
} 
///<summary>
///GetsConnectionoutofWeb.config 
///</summary>
///<returns>ReturnsSqlConnection</returns>
publicstaticSqlConnectionGetConnection() 
{ 
if(connStr==string.Empty) 
{ 
AppSettingsReaderconfigurationAppSettings=newAppSettingsReader(); 
connStr="DataSource=CXL-DC6F5F6CA80; 
POOLING=FALSE;database=SLRiaTest; 
UserID=sa;Password=123456"; 
} 
SqlConnectionconn=newSqlConnection(connStr); 
conn.Open(); 
returnconn; 
} 
///<summary>
///Getsdataoutofdatabaseusingaplaintextstringcommand 
///</summary>
///<paramname="sql">stringcommandtobeexecuted</param>
///<returns>DataTablewithresults</returns>
staticpublicDataSetGetdata(stringsql) 
{ 
using(SqlConnectionconn=GetConnection()) 
{ 
using(SqlTransactiontrans=conn.BeginTransaction(m_isoLevel)) 
{ 
try 
{ 
using(SqlCommandcmd=conn.CreateCommand()) 
{ 
if(sql!=null) 
{ 
sqlsql=sql.ToLower().Replace("<;",""); 
//.Replace(Convert.ToChar(32).ToString(),"&nbsp;").Replace("","&nbsp;").Replace("%32","&nbsp;").Replace("%20","&nbsp;"); 
sqlsql=sql.Replace(">;",""); 
sqlsql=sql.Replace("script",""); 
sqlsql=sql.Replace("object",""); 
sqlsql=sql.Replace("applet",""); 
sqlsql=sql.Replace("[",""); 
sqlsql=sql.Replace("]",""); 
sqlsql=sql.Replace("execute",""); 
sqlsql=sql.Replace("exec",""); 
sqlsql=sql.Replace("union",""); 
sqlsql=sql.Replace("drop",""); 
sqlsql=sql.Replace("delete",""); 
//sqlsql=sql.Replace("chr",""); 
//sqlsql=sql.Replace("mid",""); 
sqlsql=sql.Replace("truncate",""); 
sqlsql=sql.Replace("nchar",""); 
//sqlsql=sql.Replace("varchar",""); 
//sqlsql=sql.Replace("char",""); 
sqlsql=sql.Replace("alter",""); 
//sqlsql=sql.Replace("cast",""); 
sqlsql=sql.Replace("exists",""); 
sqlsql=sql.Replace("update",""); 
} 
cmd.Transaction=trans; 
cmd.CommandType=CommandType.Text; 
cmd.CommandText=sql; 
using(DataSetds=newDataSet()) 
{ 
using(SqlDataAdapterda=newSqlDataAdapter()) 
{ 
da.SelectCommand=cmd; 
da.SelectCommand.Connection=conn; 
da.Fill(ds); 
returnds; 
} 
} 
} 
} 
finally 
{ 
trans.Commit(); 
} 
} 
} 
} 
#endregion 
} 

第九步:鼠标右键点击SLGetDataFromWCFRIA项目“添加服务引用”即引用刚才我们编写的WCF服务。

第十步:添加一个UserInfo的实体类集合。代码如下:

///<summary>
///用户实体类 
///</summary>
publicclassUserInfo 
{ 
privatestring_ID; 
privatestring_UserName; 
privatestring_UserAddr; 
privatestring_UserTel; 
publicstringID 
{ 
get{return_ID;} 
set{_ID=value;} 
} 
publicstringUserName 
{ 
get{return_UserName;} 
set{_UserName=value;} 
} 
publicstringUserAddr 
{ 
get{return_UserAddr;} 
set{_UserAddr=value;} 
} 
publicstringUserTel 
{ 
get{return_UserTel;} 
set{_UserTel=value;} 
} 
} 

第十一步:点击MainPage.xaml文件,添加一个DataGird控件命名为grShow,在MainPage.xaml.cs文件中编写以下代码获取WCF RIA services读取到的数据库数据:

publicpartialclassMainPage:UserControl 
{ 
publicMainPage() 
{ 
InitializeComponent(); 
//创建一个代理类的实例 
SLWCFRIAClientclient=newSLWCFRIAClient(); 
//调用GetData方法并加载事件 
client.GetDataAsync(); 
client.GetDataCompleted+=newEventHandler<GetDataCompletedEventArgs>(client_GetDataCompleted); 
} 
publicList<UserInfo>userList=newList<UserInfo>(); 
voidclient_GetDataCompleted(objectsender,GetDataCompletedEventArgse) 
{ 
using(XmlReaderxReader=XmlReader.Create(newStringReader(e.Result))) 
{ 
//XmlReader读取XML数据 
while(xReader.ReadToFollowing("Table")) 
{ 
xReader.ReadToDescendant("ID"); 
stringid=xReader.ReadElementContentAsString(); 
xReader.ReadToNextSibling("UserName"); 
stringusername=xReader.ReadElementContentAsString(); 
xReader.ReadToNextSibling("UserAddr"); 
stringuseraddr=xReader.ReadElementContentAsString(); 
xReader.ReadToNextSibling("UserTel"); 
stringusertel=xReader.ReadElementContentAsString(); 
//实例化类并添加进实体类List<>
UserInfouinfo=newUserInfo(){ID=id,UserName=username,UserAddr=useraddr,UserTel=usertel}; 
userList.Add(uinfo); 
} 
this.grShow.ItemsSource=userList; 
} 
} 
} 

最后我们看最后的效果图,本实例采用VS2010+Silverlight 4.0+MS SQL SERVER 2008,复制下述网址 (http://files.cnblogs.com/chengxingliang/SLGetDataFromWCFRIA.rar)即可下载本实例源码和示例数据库

原文链接:https://77isp.com/post/7505.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。