SqlCommandBuilder
生活随笔
收集整理的這篇文章主要介紹了
SqlCommandBuilder
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SqlCommandBuilder
作用:c#中用來批量更新數據庫 用法:一般和adapter結合使用。 例: SqlConnection conn = new SqlConnection(strConnection));//連接數據庫 SqlDataAdapter myAdapter = new SqlDataAdapter();//new一個adapter對象 SqlCommand myCommand = new SqlCommand("select * from "+strTblName),(SqlConnection) conn); //cmd SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter); //new 一個 SqlCommandBuilder myAdapter.InsertCommand = myCommandBuilder .GetInsertCommand();//插入 myAdapter.UpdateCommand = myCommandBuilder .GetUpdateCommand();//更新 myAdapter.DeleteCommand = myCommandBuilder .GetDeleteCommand();//刪除 conn.Open();//打開數據庫 myAdapter.Update(ds); //更新ds到數據庫 conn.Close();//關閉數據庫 何時使用: a. 有時候需要緩存的時候,比如說在一個商品選擇界面,選擇好商品,并且進行編輯/刪除/更新后, 最后一并交給數據庫,而不是每一步操作都訪問數據庫,因為客戶選擇商品可能進行n次編輯/刪除 更新操作,如果每次都提交,不但容易引起數據庫沖突,引發錯誤,而且當數據量很大時在用戶執行 效率上也變得有些慢 b.有的界面是這樣的有的界面是這樣的,需求要求一定用緩存實現,確認之前的操作不提交到庫,點擊 頁面專門提交的按鈕時才提交商品選擇信息和商品的其它信息. 我經常遇到這樣的情況 c.有些情況下只往數據庫里更新,不讀取. 也就是說沒有從數據庫里讀,SqlDataAdapter也就不知道是 更新哪張表了,調用Update就很可能出錯了。這樣的情況下可以用SqlCommandBuilder 了 (此段參考了他人所作) d.在使用adapter的時候如果不是用設計器的時候,并且要用到adapter.Update()函數的時候,這時候要注意 SqlCommandBuilder必須要有 常見錯誤: 一些初學者經常會在使用adapter的時候忘了使用SqlCommandBuilder,即使用了也會忘了用 myAdapter.UpdateCommand = myCommandBuilder .GetUpdateCommand();//更新, 還自以為是很對,感覺煩躁不可救藥。 摘自msdn The following example uses the derived class, OleDbDataAdapter, to update the data source. C# public DataSet CreateCmdsAndUpdate(string connectionString, string queryString) { using (OleDbConnection connection = new OleDbConnection(connectionString)) { OleDbDataAdapter adapter = new OleDbDataAdapter(); adapter.SelectCommand = new OleDbCommand(queryString, connection); OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter); connection.Open(); DataSet customers = new DataSet(); adapter.Fill(customers); //code to modify data in dataset here adapter.Update(customers); return customers; } }
轉載于:https://www.cnblogs.com/rjxiaozhou/archive/2010/06/25/1765178.html
總結
以上是生活随笔為你收集整理的SqlCommandBuilder的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Discuz!NT负载均衡方案
- 下一篇: CRC16-循环冗余校验