开发者

How to create a .NET web service to insert data in SQL Server 2008

I am finding it difficult to implement a .NET web service to insert data in my database created in SQL Server 2008 . I am stuck after implementing the following code :

namespace DataService
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]

    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld(String entity)
        {
            String firstName = "";
            SqlConnection myConnection = new SqlConnection(
                @"Data Source=.\SQLEXPRESS;" + 
                @"Initial Catalog=student;User ID=sa;Password=123");
            try
            {
                myConnection.Open();
                SqlCommand myCommand = new SqlCommand();
                myCommand.Connection = myConnect开发者_开发知识库ion;
                myCommand.CommandText = "insert into stud values " +
                    "stud_name = '" + firstName + "'";

                SqlDataReader myReader = myCommand.ExecuteReader();

                //while
                if (myReader.Read())
                {
                    firstName = myReader["stud_name"].ToString();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            { 
                myConnection.Close();
            }

            return firstName;
        }
    }
}

Here entity is the JSONArray i get in the form:

[{"key0":"john","key2":"ann","key1":"joe"}]

I need to insert each value for eg "john" in the database table.


Parth_90:

First, if you are getting a JSONArray from the client side, I suggest you Deserialize it first in a List

JavascripSerializer js = new JavascriptSerializer<List<sring>>();
List<string> recordsToInsert= js.Deserialize(entity);

Then you can insert every record in the table by either looping through them and enclosing everything in a Transaction.

foreach(name in recordsToInsert)
{
 //perform the table insert here... 
 //Your SQL code seems correct to me. 
}

Improvement: Enclose the insert statements in a SQLTransaction.

EDIT: Adding some code demonstrating how to Deserialize the example JSON string provided in the question:

private static void DoSerializationTest()
    {
        string entity="{\"key0\":\"john\",\"key2\":\"ann\",\"key1\":\"joe\"}";
        JavaScriptSerializer js = new JavaScriptSerializer();

        Dictionary<string,string> result= js.Deserialize<Dictionary<string,string>>(entity);
        foreach (var item in result)
        {
            Console.WriteLine("Value: "+item.Value);
            Console.WriteLine("Key :"+item.Key);
        }
    }


You need to execute your command with ExecuteNonQuery(); ExecuteReader is for when you execute a select to get data from the database.

  SqlCommand myCommand = new SqlCommand();
                    myCommand.Connection = myConnection;
                    myCommand.CommandText = "insert into stud values " +
                        "stud_name = '" + firstName + "'";
     if(myCommand.ExecuteNonQuery() > 0)
     {
         //The command executed with affected rows > 0, OK.
     }
     else
     {
         //No rows affected by the execution. Error management.
     }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜