我正在尝试更新MS Access中的表,但更新操作不起作用,我没有收到错误。
rowsAffected
为0,因此没有更新。
这是我的代码:
public bool UpdateAddress(AddressModel address)
{
using (OleDbCommand dbCommand = new OleDbCommand())
{
// Set the command object properties
dbCommand.Connection = new OleDbConnection(this.ConnectionString);
dbCommand.CommandType = CommandType.Text;
dbCommand.CommandText = "Update Addresses " +
" Set [Street] = @Street, [PostalCode] = @PostalCode, " +
" [City] = @City, [Contact] = @Contact"+
" Where [Address_ID] = @Address_ID";
// Add the input parameters to the parameter collection
dbCommand.Parameters.AddWithValue("@Street", address.Street);
dbCommand.Parameters.AddWithValue("@PostalCode", address.PostalCode);
dbCommand.Parameters.AddWithValue("@City", address.City);
dbCommand.Parameters.AddWithValue("@Address_ID", address.Address_ID);
dbCommand.Parameters.AddWithValue("@Contact", address.Contact);
// Open the connection, execute the query and close the connection
dbCommand.Connection.Open();
var rowsAffected = dbCommand.ExecuteNonQuery();
dbCommand.Connection.Close();
return rowsAffected > 0;
}
}
AddressModel-Class:
public class AddressModel
{
public Int64 Address_ID { get; set; }
public Int64 Customer_ID { get; set; }
public string Street { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Contact { get; set; }
public bool FirstAddress { get; set; }
}
可能是什么问题?
答案 0 :(得分:4)
使用System.Data.OleDb
时,参数严格位置。 OleDb忽略参数 names ,只关注参数占位符在CommandText中出现的顺序。因此,您需要.Add
或.AddWithValue
参数的顺序与它们在CommandText中显示的顺序完全相同。
在您的情况下,您需要颠倒最后两个dbCommand.Parameters.AddWithValue
语句的顺序:@Address_ID
必须是添加的最后一个参数,因为它的占位符在CommandText中最后出现。