ASP.Net Web服务与SQL Server数据库的连接数据库、Net、ASP、Web

2023-09-04 00:33:13 作者:光与影之间没有交点°

我在ASP.Net Web服务一个完整的初学者任何人都可以指向我,我也好实现Web服务与SQL Server数据库的连接好的教程?

I'm a complete beginner in ASP.Net webservices can anyone point me to a good tutorial by which I may implement a web service with SQL Server database connectivity?

在此先感谢

推荐答案

到的Visual Studio>新建项目(选择.Net框架的 3.5 )> ASP.net Web服务应用程序 这将创建一个的HelloWorld 例如像

1. Create the Project in Visual Studio

go to Visual Studio>New Project(select .Net Framework 3.5) >ASP.net Web Service Application This will create a web service with a HelloWorld example like

    public string HelloWorld()
    {
        return "Hello World";
    }

2。创建一个数据库,并获取连接字符串

3。定义的WebMethod

要创建一个可通过客户端通过网络访问的新方法,在创建函数 [WebMethod的] 标记。

using语句添加像

add using statements like

using System.Data;
using System.Data.SqlClient;

创建一个的SqlConnection 喜欢

SqlConnection con = new SqlConnection(@"<your connection string>");

创建的SqlCommand 喜欢

 SqlCommand cmd = new SqlCommand(@"<Your SQL Query>", con);

通过调用打开连接

open the Connection by calling

con.Open();

在执行查询的try-catch 阻止这样的:

Execute the query in a try-catch block like:

try
        {
            int i=cmd.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception e)
        {
            con.Close();
            return "Failed";

        }

记住的ExecuteNonQuery()不返回游标它只返回受影响的行数, 为选择操作,其中它需要一个DataReader,使用 SqlDataReader的喜欢

Remember ExecuteNonQuery() does not return a cursor it only returns the number of rows affected, for select operations where it requires a datareader,use an SqlDataReader like

SqlDataReader dr = cmd.ExecuteReader();

和使用像

using (dr)
            {
                while (dr.Read())
                {
                    result = dr[0].ToString();



                }
                dr.Close();
                con.Close();

            }