SQL Server - 如何使用 SqlDataAdapter 在 C# 中更新多行
本文关键字:更新 SqlDataAdapter Server 何使用 SQL | 更新日期: 2023-09-27 17:55:34
我使用 SqlDataAdapter
和 SqlCommandBuilder
对 SQL Server 数据库中的行执行 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
我找到了原因,一列设置了日期时间类型。因此,此列不会保存到数据库中。