WCF Web Services + 連接 Database Insert Record 方法 (SOAP Server Side / SOAP Client Side)

 
WCF Web Services + 連接 Database Insert Record 方法 (SOAP Server Side / SOAP Client Side)
 
(SOAP Server)

   IService1.cs
 
   using System;
   using System.Collections.Generic;
   using System.Runtime.Serialization;
   using System.ServiceModel;
 
   namespace WcfService1
   {
 
      // 注意: 您可以使用 [重構] 功能表上的 [重新命名] 命令同時變更程式碼和組態檔中的介面名稱 “IService1″。
      [ServiceContract]
      public interface IService1
      {
         [OperationContract]
         void InsertItem(int ID, String Text);
 
         // TODO: 在此新增您的服務作業
      }
 
   }
 

 

   Service1.svc.cs
 
   using System;
   using System.Collections.Generic;
   using System.Text;
   using System.Data.SqlClient;
 
   namespace WcfService1
   {
      // 注意: 您可以使用 [重構] 功能表上的 [重新命名] 命令同時變更程式碼、svc 和組態檔中的類別名稱 "Service1"。
      public class Service1 : IService1
      {
         public void InsertItem(int ID, String Text)
         {
 
            String connectionString1 = "Data Source=.\\SqlExpress; Initial Catalog=Soccer; Integrated Security=SSPI";
            SqlConnection con1 = new SqlConnection(connectionString1);
            con1.Open();
 
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO dbo.Test_A (ID, Text) VALUES (" + ID + ",'" + Text + "');");
 
            SqlCommand cmd1 = new SqlCommand(sb.ToString(), con1);
            cmd1.ExecuteNonQuery();
 
            cmd1.Dispose();
            con1.Dispose();
 
         }
      }
   }
 

 
(SOAP Client – 需自行增加 Service References)

   Default.aspx.cs
 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Web;
   using System.Web.UI;
   using System.Web.UI.WebControls;
   using WebApplication9.ServiceReference1;
 
   namespace WebApplication9
   {
      public partial class _Default : System.Web.UI.Page
      {
         protected void Page_Load(object sender, EventArgs e)
         {
            Service1Client WCFObj = new Service1Client();
            WCFObj.InsertItem(200, "Text 200");
            WCFObj.Close();
         }
      }
   }