Web服务初探:用Demo学Web服务系列(6)——断开模式访问数据库的Web服务
通过上次的《Web服务初探:用Demo学Web服务系列(5)——连接模式访问数据库的Web服务》学习,我们已经知道了,Web Services是如何从数据库中来使用连接模式访问数据库来进行操作。下面我们来看看在上次的讨论中所讲述WebService再次改变,让这个WebService能变成断开模式访问数据库的Web Services。
这次我们要改变上次的WebService时并不是在原来的方法上做改变,而是在WebService中添加了一个新方法,并且在我们建立的C/S程序工程中也加入了一个新的Windows Form来调用这个新加的方法。
一、在前面的WebService中加入下面的方法,代码如下:
二、C/S工程中添加窗体并在“查询”按钮中加入相关代码,窗体和代码如下:
1、窗体中加入一个TextBox、一个Button和一个DataGridView,如下图:

2、在其中的“查询”按钮下代码为:
这次我们要改变上次的WebService时并不是在原来的方法上做改变,而是在WebService中添加了一个新方法,并且在我们建立的C/S程序工程中也加入了一个新的Windows Form来调用这个新加的方法。
一、在前面的WebService中加入下面的方法,代码如下:
1
[WebMethod]
2
public DataSet SelectUser(string UserName)
3
{
4
Configuration WebConfig = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
5
DataSet DS = new DataSet("WSDemoDB");
6
DataTable DT = new DataTable("UserTable");
7
DS.Namespace = "http://tempuri.org/DataSet";
8
DS.Tables.Add(DT);
9
if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
10
{
11
ConnectionStringSettings ConStr = WebConfig.ConnectionStrings.ConnectionStrings["WSConStringSQL"];
12
if (ConStr != null)
13
{
14
SqlConnection SqlCon = new SqlConnection(ConStr.ConnectionString);
15
SqlCommand SqlCom = new SqlCommand("SELECT 用户ID, 用户名称, 用户密码, 用户姓名, 用户性别, 密码提示问题, 问题答案 FROM 用户表 WHERE (用户名称 LIKE '%' + @用户名称 + '%')", SqlCon);
16
SqlCom.Parameters.Add("@用户名称", SqlDbType.NVarChar);
17
SqlCom.Parameters["@用户名称"].Value = UserName;
18
SqlDataAdapter SqlDA = new SqlDataAdapter(SqlCom);
19
try
20
{
21
SqlCon.Open();
22
SqlDA.Fill(DT);
23
}
24
finally
25
{
26
SqlDA.Dispose();
27
SqlCom.Dispose();
28
SqlCon.Close();
29
SqlCon.Dispose();
30
}
31
}
32
}
33
return DS;
34
}
WebService方法说明:添加的方法名为SelecUser,其中需要获得一个参数UserName。此方法返回一个根据传入的UserName查询到的相关用户信息的DataSet。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
二、C/S工程中添加窗体并在“查询”按钮中加入相关代码,窗体和代码如下:
1、窗体中加入一个TextBox、一个Button和一个DataGridView,如下图:
2、在其中的“查询”按钮下代码为:
1
private void Btn_SelectUser_Click(object sender, EventArgs e)
2
{
3
MyServ.MyServiceClass MyWebServ = new MyServ.MyServiceClass();
4
DataSet DS = new DataSet();
5
DS = MyWebServ.SelectUser(TB_User.Text);
6
if (DS.Tables.Count > 0)
7
{
8
DGV_UserView.DataSource = DS.Tables["UserTable"];//此处也可写成:DGV_UserView.DataSource = DS.Tables[0];
9
}
10
else
11
{
12
MessageBox.Show("没有查询到所需要的数据!");
13
}
14
}
这样我们完成了此次WebService的调用。2
3
4
5
6
7
8
9
10
11
12
13
14
代码说明:跟其他的调用一样我们需要实例化WebService的代理类,然后定义一个DataSet用来接收WebService中SelectUser的返回值,最后将返回的DataSet绑定到DGV_UserView上。
本文转自刚刚博客园博客,原文链接:http://www.cnblogs.com/lijigang/archive/2006/11/18/564853.html,如需转载请自行联系原作者