ASP.Net Web Service with SQL Server Database Connection

I'm a complete newbie to ASP.Net web services, can someone point me to a good tutorial with which I can implement a web service with a SQL Server database connection?

Thanks in advance

+4
source share
2 answers

1. Create a 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 an example of HelloWorld like

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

2. Create a database and get a connection string

3. Define WebMethod

To create a new method that clients can access over the network, create functions in the [WebMethod] tag.

4.Common structure for using database connection

add expressions such as

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

Create SqlConnection as

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

create SqlCommand as

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

open Connection by calling

 con.Open(); 

Run the query in a try-catch , for example:

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

Remember ExecuteNonQuery() does not return a cursor, it returns the number of rows affected, for select operations where a datareader is required, use SqlDataReader as

 SqlDataReader dr = cmd.ExecuteReader(); 

and use the reader as

 using (dr) { while (dr.Read()) { result = dr[0].ToString(); } dr.Close(); con.Close(); } 
+6
source

Here is a video in which you will learn how to retrieve data from MS SQL Server in the ASP.NET web service .

+2
source

Source: https://habr.com/ru/post/1501397/


All Articles