2011-07-20 35 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是你的朋友。