Using adapter.Update
I'm trying to Update a table but I keep getting the exception : Update unable to find TableMapping...
I even tried minimizing my code but I still don't see the problem
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)
{
SqlC开发者_运维知识库onnection connection = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(strSql, connection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
new SqlCommandBuilder(adapter);
adapter.Update(ds, tablename);
}
And I even tried removing the for, What could be the problem?
Based on how your code is designed, you should be using an SqlCommand object to perform the update without the SqlDataAdapter. The SqlDataAdapter is being used wrong, and it's unnecessary based on how your code is constructed.
The construction for the DataAdapter
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
sets the command (cmd) as the SELECT command for the DataAdapter, not the Update command. (A DataAdapter has an insert, update, delete, and select command)
Try this instead:
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();
}
}
Alternately, you could keep most of your code and set the update command properly - add a line that says
adapter.UpdateCommand = strSql;
just before the call to "Update".
精彩评论