我是ASP.Net webservices的完整入门者,谁能给我指出一个好的教程,通过它我可以实现与SQL Server数据库连接的Web服务?
提前致谢
转到“ Visual Studio”>“新建项目”(选择.Net Framework 3.5)>“ ASP.net Web服务应用程序”,这将创建一个带有以下HelloWorld
示例的Web服务
public string HelloWorld()
{
return "Hello World";
}
要创建客户端可以通过网络访问的新方法,请在[WebMethod]
标签下创建函数。
添加使用语句,例如
using System.Data;
using System.Data.SqlClient;
创建一个SqlConnection
赞
SqlConnection con = new SqlConnection(@"<your connection string>");
创造你的SqlCommand
喜欢
SqlCommand cmd = new SqlCommand(@"<Your SQL Query>", con);
通过调用打开连接
con.Open();
在如下代码try-catch
块中执行查询:
try
{
int i=cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception e)
{
con.Close();
return "Failed";
}
请记住ExecuteNonQuery()
,不返回游标,它仅返回受影响的行数,对于select
需要数据读取器的操作,请使用SqlDataReader
like
SqlDataReader dr = cmd.ExecuteReader();
并像这样使用读者
using (dr)
{
while (dr.Read())
{
result = dr[0].ToString();
}
dr.Close();
con.Close();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句