Create and use WebService with VS2012 (connect to SQL Server)

Source: Internet
Author: User

1. Create the "ASP. Web Application". Open the VS2012 and select "File" = "new" + "project" to bring up the "New Project" window ; then, Select Web "=" ASP. NET empty Web application, you can set up a new project with a name, location, solution name, and then click OK button to create an ASP.

2. Open Server Explorer, right-click Data Connections, select Add Connection (A) ..., and the Add Connection dialog box pops up.


3. In the "Add Connection" dialog box, enter "server name (E)", select "Login to the server" and fill in the appropriate information, then select "Connected to the database", then you can click the "Test Connection" button, test the connection is successful, and then click the "OK" button to add success.


4. The connection was successfully added.


5. Add a database connection. Create the folder "DB" first, and then add a "SQLServerDB.cs" class to connect to the SQL Server database.


6. Add the following code to the created SQLServerDB.cs:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >using system;using system.collections.generic;using system.data.sqlclient;using System.Linq;using System.Web; namespace androidwebservice.db{///<summary>////    for Operations of SQL Server database///    </summary>    public class Sqlserverdb    {        //Connection Database public        SqlConnection Sqlcon;        Connection database string public string        strSQL = @ "Data source=172.17.2.64;initial Catalog=vjudge; Persist Security info=true; User Id=sa; password=1234 ";        Default constructor public        Sqlserverdb () {            if (Sqlcon = = null) {                Sqlcon = new SqlConnection ();                sqlcon.connectionstring = strSQL;                Sqlcon.open ();            }        }        public void Close () {            if (Sqlcon! = null) {                sqlcon.close ();                Sqlcon.dispose ();}}}    </span>


7. Add a database operation. Create the folder "action" and add a "SQLServerAction.cs" class to the database operation.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >using androidwebservice.db;using system;using system.collections.generic;using System.Data.SqlClient;using System.linq;using system.web;namespace androidwebservice.action{public class Usersqlserveraction {SQL Server        DB db = new Sqlserverdb ();        <summary>///judgment User Login///</summary>//<param name= "UserID" ></param> <param name= "Password" ></param>///<returns></returns> public string Userlo Gin (String UserID, String Password) {String strSQL = "Select nickname from Dbo.users where Userid= '" +userid+            "' and password= '" +password+ "'";            SqlCommand SQLCMD = new SqlCommand (strSQL, Db.sqlcon);            SqlDataReader Sqlreader = Sqlcmd.executereader (); if (Sqlreader.read ()) {return sqlreader[0].            ToString ();        } return "";    }//<summary>    Back to all Users list///</summary>//<returns></returns> public list<string> I            Ndex () {list<string> user = new list<string> ();            String strSQL = "SELECT * from Dbo.users";            SqlCommand SQLCMD = new SqlCommand (strSQL, Db.sqlcon);            SqlDataReader Sqlreader = Sqlcmd.executereader (); while (Sqlreader.read ()) {User. ADD (Sqlreader[0].                ToString ()); User. ADD (Sqlreader[1].                ToString ()); User. ADD (Sqlreader[2].                ToString ()); User. ADD (Sqlreader[3].            ToString ());        } return user;        }///<summary>//return user details//</summary>//<returns></returns>            Public list<string> Detail () {list<string> user = new list<string> ();            String strSQL = "SELECT * from Dbo.users"; SqlCommand SQLCMD =New SqlCommand (strSQL, Db.sqlcon);            SqlDataReader Sqlreader = Sqlcmd.executereader (); if (Sqlreader.read ()) {User. ADD (Sqlreader[0].                ToString ()); User. ADD (Sqlreader[1].                ToString ()); User. ADD (Sqlreader[2].                ToString ()); User. ADD (Sqlreader[3].            ToString ());        } return user; }///<summary>//create User///</summary>//<param name= "UserID" ></param&        Gt <param name= "nickname" ></param>//<param name= "PhoneNumber" ></param>//<p Aram Name= "Password" ></param>///<returns></returns> public string Create (string User Id,string Nickname, String PhoneNumber, String Password) {String strSQL = "Select nickname from Dbo.users whe            Re userid= ' "+ UserID +" ' ";            SqlCommand SQLCMD = new SqlCommand (strSQL, Db.sqlcon); SqldatareAder Sqlreader = Sqlcmd.executereader (); if (Sqlreader.read ()) {return "already exists <" + UserID + "> user!                         ";            } sqlreader.close ();            strSQL = "INSERT into dbo.users values ('" + UserID + "', '" + Nickname + "', '" + PhoneNumber + "', '" + Password + "')";            SqlCommand Sqlcmdin = new SqlCommand (strSQL, Db.sqlcon);            Sqlcmdin.executenonquery (); Return "added successfully!        "; }///<summary>//delete user///</summary>//<param name= "UserID" ></param&        Gt <returns></returns> public string Delete (string UserID) {string strSQL = "Sele            CT nickname from dbo.users where userid= ' "+ UserID +" ' "; using (SqlCommand SQLCMD = new SqlCommand (strSQL, Db.sqlcon)) {SqlDataReader Sqlreader = sqlcmd .                ExecuteReader ();             if (!sqlreader.read ()) {       Return "does not exist for this user!                ";            } sqlreader.close ();            } strSQL = "Delete from dbo.users where userid= '" + UserID + "'";            using (SqlCommand Sqlcmdin = new SqlCommand (strSQL, Db.sqlcon)) {sqlcmdin.executenonquery (); } return "deleted successfully!        "; }}}</span>

8. Add a Web service. Right-click the project name, select Add = + new item, and the Add New Item window pops up. Select the Web and Web Services option to modify the name for the new item, and then click the Add button to successfully add a Web services item with an. asmx suffix. Open the new Web Service service and modify the code as follows:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >using androidwebservice.action;using system;using system.collections.generic;using System.Linq;using System.Web ; using System.web.services;namespace androidwebservice{//<summary>//Summary description for Usersqlserve Rwebservice//</summary> [WebService (Namespace = "http://tempuri.org/")] [webservicebinding (ConformsTo = Wsiprofiles.basicprofile1_1)] [System.ComponentModel.ToolboxItem (false)]//To allow this Web Service to be called F     Rom script, using ASP. AJAX, uncomment the following line.    [System.Web.Script.Services.ScriptService] public class UserSQLServerWebService:System.Web.Services.WebService        {Usersqlserveraction uaction = new Usersqlserveraction ();        <summary>//Judgment Login///</summary>/<param name= "UserID" ></param> <param name= "Password" ></param>//<returns></returns> [WebMethod] public string Userlogin (string UserID, String Password) {return uacti Mnl        Userlogin (Userid,password);        }///<summary>//Show All Users list///</summary>//<returns></returns> [WebMethod] public string[] Index () {return Uaction.index ().        ToArray ();        }///<summary>//Display a User details///</summary>//<returns></returns> [WebMethod] public string[] Detail () {return Uaction.detail ().        ToArray (); }///<summary>//create User///</summary>//<param name= "UserID" ></param&        Gt <param name= "nickname" ></param>//<param name= "PhoneNumber" ></param>//<p Aram Name= "Password" ></param>///<returns></returns> [WebMethod] public string Create (String UserID, string nickname, String PhoneNumber, String Password) {return uaction.create (Us        Erid,nickname,phonenumber,password); }///<summary>//delete user///</summary>//<param name= "UserID" ></param&        Gt <returns></returns> [WebMethod] public string Delete (string UserID) {Retu        RN Uaction.delete (UserID); }}}</span>


Create and use WebService with VS2012 (connect to SQL Server)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.