C#DataTable更新多行

如何使用数据表进行多次更新?

我发现这个更新1行

我的代码:

public void ExportCSV(string SQLSyntax, string LeFile, bool Is_Ordre, int TypeDonne) { try { using (var connectionWrapper = new Connexion()) { var connectedConnection = connectionWrapper.GetConnected(); SqlDataAdapter da = new SqlDataAdapter(SQLSyntax, connectionWrapper.conn); DataSet ds = new DataSet(); da.Fill(ds, "Emp"); DataTable dt = ds.Tables["Emp"]; CreateCSVFile(dt, LeFile, Is_Ordre, TypeDonne); //Update all lines, it not save in Database foreach (DataRow row in dt.Rows) { row["IS_IMPORT"] = true; } } } catch (Exception excThrown) { throw new Exception(excThrown.Message); } } 

问题是 :

 foreach (DataRow row in dt.Rows) { row["IS_IMPORT"] = true; } 

它不会保存到数据库中。

先生,谢谢你,Stev

您正在更新内存中的值。 DataTable类不是 sql视图,而是内存表示。 Sql Data Adapter仅复制数据。

您必须将更改写回数据库。 试试这个 :

 public void ExportCSV(string SQLSyntax, string LeFile, bool Is_Ordre, int TypeDonne) { try { using (var connectionWrapper = new Connexion()) { var connectedConnection = connectionWrapper.GetConnected(); SqlDataAdapter da = new SqlDataAdapter(SQLSyntax, connectionWrapper.conn); da.UpdateCommand = connectedConnection.CreateCommand(); da.UpdateCommand.XXXX = YYYY; // construct the SQL Command DataSet ds = new DataSet(); da.Fill(ds, "Emp"); DataTable dt = ds.Tables["Emp"]; CreateCSVFile(dt, LeFile, Is_Ordre, TypeDonne); //Update all lines, it not save in Database foreach (DataRow row in dt.Rows) { row["IS_IMPORT"] = true; } da.Update(dt); } } catch (Exception excThrown) { throw new Exception(excThrown.Message); } } 

这应该有效。

您需要首先将DataAdapter上的UpdateCommand属性设置为UPDATE语句,该语句将被执行以更新数据库中的行。

然后,在更新DataTable中的值之后,需要将其传递给DataAdapter.Update()。 然后,它将为DataTable中的每个更新行执行UpdateCommand。

参考文献:

MSDN – SqlDataAdapter.Update
MSDN – SqlDataAdapter.UpdateCommand

你必须调用da.Update()