C#中SqlDataApter.update()使用經驗及技巧

来源:互联网 发布:注册会计师挂靠 知乎 编辑:程序博客网 时间:2024/05/08 20:13

我原來是用delphi7.0開發ERP系統﹐從2007年開始轉向C#2005,可是在做測試數據保存時總出現如下錯誤﹕

Update requires a valid InsertCommand when passed DataRow collection with new rows.

當時很納悶。

部分代碼如下﹕

scn.ConnectionString = GlobMsg.DbConnection;
            scn.Open();
           
            SqlCommand scmdpc_hd = new SqlCommand();
            scmdpc_hd.Connection = scn;
            scmdpc_hd.CommandText = "select * from pc_hd";
            scmdpc_hd.CommandType = CommandType.Text;

            SqlCommand scmdpc_ln = new SqlCommand();
            scmdpc_ln.Connection = scn;
            scmdpc_ln.CommandText = "select * from pc_ln";
            scmdpc_ln.CommandType = CommandType.Text;
           

            //SqlDataAdapter sda_PC_HD = new SqlDataAdapter("select * from pc_hd",scn );

            sda_PC_HD.SelectCommand = scmdpc_hd;
                    
            sda_PC_HD.Fill(ds, "pc_hd");
           
            //SqlDataAdapter sda_PC_LN = new SqlDataAdapter("select * from pc_ln",scn);
            sda_PC_LN.SelectCommand = scmdpc_ln;
           
            sda_PC_LN.Fill(ds, "pc_ln");

            dvpc_hd = ds.Tables["pc_hd"].DefaultView ;
            pc_hdDataGridView.DataSource = dvpc_hd;

            dvpc_ln = ds.Tables["pc_ln"].DefaultView;
            pc_lnDataGridView.DataSource = dvpc_ln;

==========================

if (ds.GetChanges() == null)
            {
                MessageBox.Show("is null");
                return;
            }
            //ds.EnforceConstraints = false;

//如下紅色代碼原本調試時是沒有的。仔細閱讀c#相關資料才發現﹐只要寫上此二行代碼完全搞定﹐ok.
            SqlCommandBuilder scb_pc_hd = new SqlCommandBuilder(sda_PC_HD);
            SqlCommandBuilder scb_pc_ln = new SqlCommandBuilder(sda_PC_LN);


            sda_PC_LN.Update(ds, "pc_ln");
           // sda_PC_HD.
            sda_PC_HD.Update(ds, "pc_hd");

 

=======================

總結﹕

1.為什么不能直接用sqlcommand,一定要加上一個sqlcommandbuilder﹐才可以保存?這個我不明白為什么。

2.在DELPHI中可以看到修改后的數據﹐也就是說我們調用delphi中clientdataset.delta時將出現成對的記錄﹐一條原數據記錄﹐一條修改后的數據記錄﹐而在c#中調用dataset.getchanges()時得到的是一條修改后的數據記錄﹐這有有區別了。(在delphi中這種方式可以知道我修改了哪個字段數據﹐或是將哪個數據置為空了﹐而在c#中因只有一條數據﹐沒辦法知道我修改了哪些字段)有沒有知道這個機理的朋友﹖有的話請在此留言并發表意見。

3.多交流。

4.多學習。

//引用此文章請注明﹕本文章原創作者﹕馮鵬飛(蘭鵬電腦軟件開發部總設計師)