我正在尝试更新表,但一直收到异常: Update unable to find 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,这会是什么问题呢?
发布于 2011-03-05 02:07:56
根据代码的设计方式,您应该在没有SqlDataAdapter的情况下使用SqlCommand对象来执行更新。SqlDataAdapter被错误地使用了,根据您的代码的构造方式,它是不必要的。
DataAdapter的构建
SqlDataAdapter SqlDataAdapter=新适配器(Cmd);
将命令(cmd)设置为DataAdapter的选择命令,而不是更新命令。( 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();
}
}或者,您可以保留大部分代码并正确设置update命令-添加一行如下所示
adapter.UpdateCommand = strSql;
就在调用"Update“之前。
https://stackoverflow.com/questions/5197460
复制相似问题