日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用SqlCommandBuilder

發布時間:2023/12/10 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。