我使用SqlDataAdapter
和SqlCommandBuilder
对SQL Server数据库中的行执行DML事务。
我可以在数据库中添加和删除多行但更新。
这是代码:
SqlDataAdapter da = new SqlDataAdapter(@"select top 1 * from " + tableName,
ConnectionString);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.Update(dt);
我正在尝试使用AcceptChanges
,到目前为止它无效。
答案 0 :(得分:0)
这就是我通常在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
答案 1 :(得分:0)
我找到了原因,列设置了DateTime类型。因此,此列不会保存到数据库中。