簡體   English   中英

如何創建.NET Web服務以在SQL Server 2008中插入數據

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

我發現很難實施.NET Web服務在SQL Server 2008中創建的數據庫中插入數據。 實現以下代碼后,我陷入了困境:

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 = myConnection;
                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;
        }
    }
}

這里的實體是我以以下形式獲得的JSONArray:

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

我需要在數據庫表中插入例如“ john”的每個值。

Parth_90:

首先,如果要從客戶端獲取JSONArray,建議您首先在列表中反序列化它

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

然后,您可以通過遍歷每個記錄並將所有內容括在事務中來將每個記錄插入表中。

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

改進: 將插入語句括在SQLTransaction中。

編輯 :添加一些代碼,演示如何反序列化問題中提供的示例JSON字符串:

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

您需要使用ExecuteNonQuery()執行命令。 ExecuteReader用於執行選擇以從數據庫獲取數據時。

  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.
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM