C#中如何使用SqlDataAdapter更新多行

How to use SqlDataAdapter to update multiple row in c#

我使用 SqlDataAdapterSqlCommandBuilder 对 SQL 服务器数据库中的行执行 DML 事务。

我可以在数据库中添加和删除多行但更新。

这是代码:

SqlDataAdapter da = new SqlDataAdapter(@"select top 1 * from " + tableName, 
ConnectionString);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.Update(dt);

我正在尝试使用 AcceptChanges,目前还没有用。

这是我在 C# 中通常做的事情。如果你想试试这个。

//you may put this as a direct string or in a static class when layering
//you can pass table as hard-coded value or as a parameter
String SqlQuery = "UPDATE " +
            " [tableName] " +
            " SET [Column1ToBeUpdated]=@Column1Value," +
            " [Column2ToBeUpdated]=@Column2Value" +
            " WHERE ([ColumnxWithCondition] = @Condition)";

//add OR, AND operators as per your needs
//choose the correct SqlDbType for your column data types

public bool UpdateMyTable(String SqlQuery, Someclass obj)
 {
        SqlCommand sCommand = new SqlCommand(this.SqlQuery, (new SqlConnection(ConnectionString)));

        sCommand.Parameters.Add("@Column1Value", SqlDbType.VarChar).Value = obj.col1Value;
        sCommand.Parameters.Add("@Column2Value", SqlDbType.VarChar).Value = obj.col2Value;
        sCommand.Parameters.Add("@Condition", SqlDbType.VarChar).Value = obj.condition;

        sCommand.Connection.Open();
        var rowsAffected = sCommand.ExecuteNonQuery();
        sCommand.Connection.Close();
        return rowsAffected > 0;
 }

 //if you want to see the number, you may return rowsAffected

我找到原因了,一列设置了日期时间类型。因此,此列未保存到数据库中。