【问题标题】:Using adapter.Update使用适配器。更新
【发布时间】:2011-03-04 17:58:09
【问题描述】:

我正在尝试更新表格,但我不断收到异常:更新无法找到 TableMapping...

我什至尝试最小化我的代码,但我仍然没有发现问题

Items.cs

public static void WriteDescription()
    {
        DataSet items = DAL.GetDataSet("SELECT * FROM Items");

        for (int i = 0; i < items.Tables[0].Rows.Count; i++)
                items.Tables[0].Rows[i]["Description"] = "Hello";

        DAL.UpdateDB("SELECT * FROM Items", items, "Items");
    }

Dal.cs

static public void UpdateDB(string strSql, DataSet ds, string tablename)
    {
        SqlConnection connection = new SqlConnection(ConnectionString);
        SqlCommand cmd = new SqlCommand(strSql, connection);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        new SqlCommandBuilder(adapter);
        adapter.Update(ds, tablename);
    }

我什至尝试删除 for,可能是什么问题?

【问题讨论】:

    标签: c# .net sql dataset


    【解决方案1】:

    根据您的代码设计方式,您应该使用 SqlCommand 对象来执行更新,而无需 SqlDataAdapter。 SqlDataAdapter 使用错误,根据您的代码构造方式,它是不必要的。

    DataAdapter 的构造

    SqlDataAdapter 适配器 = 新 SqlDataAdapter(cmd);

    将命令 (cmd) 设置为 DataAdapter 的 SELECT 命令,而不是 Update 命令。 (DataAdapter 有插入、更新、删除和选择命令)

    试试这个:

        static public void UpdateDB(string strSql, DataSet ds, string tablename)
        {
            SqlConnection connection = new SqlConnection(ConnectionString);
            SqlCommand cmd = new SqlCommand(strSql, connection);
            try
            {
               connection.Open();
               cmd.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
               // error hanlding code here
            }
            finally
            {
              connection.Close();
            }
        }
    

    或者,您可以保留大部分代码并正确设置更新命令 - 添加一行

    adapter.UpdateCommand = strSql;

    就在调用“更新”之前。

    【讨论】:

      猜你喜欢
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      相关资源
      最近更新 更多