4

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?

Thanks in advance

2 Answers 2

7

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. Create a Database and Obtain the connection string

3. Define WebMethod

To create a new method that can be accessed by clients over the network,create functions under [WebMethod] tag.

4.Common structure for using database connection

add using statements like

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

Create an SqlConnection like

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

create your SqlCommand like

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

open the Connection by calling

con.Open();

Execute the query in a try-catch block like:

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

        }

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();

and use the reader like

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



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

            }
Sign up to request clarification or add additional context in comments.

Comments

2

Here is a video that will walk you through how to retrieve data from MS SQL Server in ASP.NET web service.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.