【问题标题】:Problem with ADO.NET UPDATE codeADO.NET 更新代码的问题
【发布时间】:2013-08-20 01:38:15
【问题描述】:

有人可以快速浏览一下我的 ado.net 代码吗?我正在尝试从数据集中更新行,但它不起作用。我错过了一些基本的代码,它只是在逃避我。我已经验证了 DataRow 实际上有正确的数据,所以行本身是准确的。

非常感谢。

 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();

            }  

【问题讨论】:

  • 我在您的代码中没有看到您设置更新命令或用于 dbAdapter 的 sql 语句的任何地方。

标签: c# ado.net datarow


【解决方案1】:

我认为您需要在数据适配器中进行更新查询。我知道,这很糟糕......或者,您可以使用 CommandBuilder 类自动生成 CRUD 操作的查询。

示例:http://www.programmersheaven.com/2/FAQ-ADONET-CommandBuilder-Prepare-Dataset

【讨论】:

    【解决方案2】:

    您也许可以使用 SqlCommandBuilder 来提供帮助。在Fill 调用之后,添加以下语句。这会将命令生成器与数据适配器相关联,并且(如果有可用的主键)它应该为您生成更新语句。请注意,命令生成器背后有一些费用。它可能与其他所有内容无关,但它确实涉及查看表的架构信息(以获取主键信息、字段名称、字段类型等)并生成涉及所有字段的 INSERT、DELETE 和 UPDATE 语句桌子。

    SqlCommandBuilder cb = new SqlCommandBuilder(dbAdapter);
    

    【讨论】:

    • 嘘!谢谢!我有 SqlCommandBuilder,但我没有在数据中指定主键。现在效果很好。谢谢!!!
    【解决方案3】:

    等等,为什么不类似

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

    如果您一次选择一个表的所有行来更新一个,那么您可能做错了。 SQL 是你的朋友。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2015-06-16
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      相关资源
      最近更新 更多