首先新建 “ASP.NET Web 服务应用程序”,之后写个返回string 类型的方法 ,具体实现如下:
[WebMethod]
public string selectByID(int id)
{
string name = "";
SqlConnection conn = new SqlConnection ("server=.;database=test;uid=sa;pwd=sa");
DataSet ds = new DataSet();
string sql = "select * from aa where id=" + id + "";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
name = ds.Tables[0].Rows[0]["Name"].ToString();
}
return name;
}
上面就已经写好了一个webservice 方法,之后在你的项目里添加“web”引用,添加引用成功之后,就可以调用ws里面的方法了,实现如下:
protected void Button1_Click(object sender, EventArgs e)
{
//new 一个webservice 实例
Service.Service1 service = new Service1();
// selectByID 为webservice 方法
string value = service.selectByID(3);
if (value != "")
{
this.Label1.Text = value.ToString();
}
else
{
this.Label1.Text = "Null";
}
}
实现效果和数据库截图: