2011-03-04 20 views
0

我试图更新表,但我不断收到异常:更新找不到TableMapping ...使用adapter.Update

我甚至尝试尽量减少我的代码,但我仍然没有看到问题

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

而且我甚至试图消除的,有什么合作这是问题吗?

回答

0

根据您的代码的设计方式,您应该使用SqlCommand对象来执行不带SqlDataAdapter的更新。 SqlDataAdapter被错误地使用,根据代码的构建方式,这是不必要的。

构造为DataAdapter的

SqlDataAdapter的适配器=新 SqlDataAdapter的(CMD);

将命令(cmd)设置为DataAdapter的SELECT命令,而不是Update命令。 (A 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;

就在呼叫“更新”之前。