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(); }
source share