使用SqlCommandBuilder
使用命令構造器添加行
View Code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient;namespace PersistAddsBuilder {class Program{static void Main(string[] args){string connString = @"server=.;integrated security=true;database =northwind";string qry = @"select * from employees where country='UK'";SqlConnection conn = new SqlConnection(connString);try{SqlDataAdapter da = new SqlDataAdapter();da.SelectCommand = new SqlCommand(qry, conn);SqlCommandBuilder cb = new SqlCommandBuilder(da);DataSet ds = new DataSet();da.Fill(ds, "employees");DataTable dt = ds.Tables["employees"];DataRow newRow = dt.NewRow();newRow["firstname"] = "Roy";newRow["lastname"] = "Beatty";newRow["titleofcourtesy"] = "Sir";newRow["city"] = "Birmingham";newRow["country"] = "UK";dt.Rows.Add(newRow);foreach (DataRow row in dt.Rows){Console.WriteLine("{0} {1} {2}", row["firstname"].ToString().PadRight(15), row["lastname"].ToString().PadLeft(25), row["city"]);}da.Update(ds, "employees");}catch (Exception e){Console.WriteLine("Error: " + e);}finally{conn.Close();}Console.ReadKey();}} }示例說明
最值得注意的地方并不是添加的一行代碼,而是該代碼所替代的代碼,下面的一行語句:
使下面的所有代碼變得多余:
string ins = @"insert into employees(firstname,lastname,titleofcourtesy,city,country)
??????????? values(@firstname,@lastname,@titleofcourtesy,@city,@country)";
SqlCommand cmd = new SqlCommand(ins, conn);
??????????????? cmd.Parameters.Add("@firstname", SqlDbType.NVarChar, 10, "firstname");
??????????????? cmd.Parameters.Add("@lastname", SqlDbType.NVarChar, 20, "lastname");
??????????????? cmd.Parameters.Add("@titleofcourtesy", SqlDbType.NVarChar, 25, "titleofcourtesy");
??????????????? cmd.Parameters.Add("@city", SqlDbType.NVarChar, 15, "city");
??????????????? cmd.Parameters.Add("@country", SqlDbType.NVarChar, 15, "country");
??????????????? da.InsertCommand = cmd;
顯然,使用命令構建器比手動編寫SQL更好,但是它們只能處理一個表,底層的數據庫表必須有主鍵或唯一鍵。另外,數據適配器的SelectCommand屬性必須有一個包含主鍵的查詢。
轉載于:https://www.cnblogs.com/tanding/archive/2012/07/23/2604730.html
總結
以上是生活随笔為你收集整理的使用SqlCommandBuilder的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下时间同步的两种方法分享
- 下一篇: 如何在IDEA中导出jar包