2011-07-20 36 views
1

有人可以快速瀏覽我的ado.net代碼嗎?我正在嘗試更新數據集中的行,但它不起作用。我錯過了一些基本的代碼片段,它只是逃避我。我已經證實DataRow實際上有正確的數據,所以行本身是準確的。問題與ADO.NET更新代碼

非常感謝提前。

try 
      { 
       //basic ado.net objects 
       SqlDataAdapter dbAdapter = null; 
       DataSet returnDS2 = new DataSet(); 

       //a new sql connection 
       SqlConnection myConn = new SqlConnection(); 
       myConn.ConnectionString = "Server=myserver.mydomain.com;" 
        + "Database=mydatabase;" 
        + "User ID=myuserid;" 
        + "Password=mypassword;" 
        + "Trusted_Connection=True;"; 

       //the sqlQuery 
       string sqlQuery = "select * from AVLUpdateMessages WHERE ID = 21"; 

       //another ado.net object for the command 
       SqlCommand cmd = new SqlCommand(); 
       cmd.Connection = myConn; 
       cmd.CommandText = sqlQuery; 

       //open the connection, execute the SQL statement and then close the connection. 
       myConn.Open(); 

       //instantiate and fill the sqldataadapter 
       dbAdapter = new SqlDataAdapter(cmd); 
       dbAdapter.Fill(returnDS2, @"AVLUpdateMessages"); 

       //loop through all of the rows; I have verified that the rows are correct and returns the correct data from the db 
       for (int i = 0; i <= returnDS2.Tables[0].Rows.Count - 1; i++) 
       { 
        DataRow row = returnDS2.Tables[0].Rows[i]; 
        row.BeginEdit(); 
        row["UpdatedText"] = @"This is a test..."; 
        row.EndEdit(); 
       } 

       //let's accept the changes 
       dbAdapter.Update(returnDS2, "AVLUpdateMessages"); 
       returnDS2.AcceptChanges(); 

       myConn.Close(); 

      } 
+2

我沒有看到代碼中設置Update命令或sql語句用於dbAdapter的任何地方。 – David

回答

0

您可能可以使用SqlCommandBuilder來幫忙。在Fill調用之後,添加以下語句。這將使命令生成器與數據適配器相關聯(如果有主鍵可用),它應該爲您生成更新語句。請注意,在命令生成器後面有一些費用。它可能與其他所有東西沒什麼關係,但它確實涉及查看錶的表格信息(獲取主鍵信息,字段名稱,字段類型等),並生成涉及所有字段的INSERT,DELETE和UPDATE語句桌子。

SqlCommandBuilder cb = new SqlCommandBuilder(dbAdapter); 
+0

Boo ya!謝謝!我有SqlCommandBuilder,但是我沒有在數據中指定主鍵。現在它運作良好。謝謝!!! – jdb1a1

+0

@JDB:很酷。我很高興你能工作。 –

0

等待,爲什麼不喜歡

update AVLUpdateMessages set UpdatedText = 'This is a test...' where id = 21 

如果你通過一個表格來更新一次一個的所有行採摘,你可能做錯誤。 SQL是你的朋友。