日期:2014-05-18 浏览次数:20511 次
//// Update the Employee by ID.// This method assumes that ConflictDetection is set to OverwriteValues.publicint UpdateEmployee(NorthwindEmployee employee)
{
if (String.IsNullOrEmpty(employee.FirstName))
thrownew ArgumentException("FirstName cannot be null or an empty string.");
if (String.IsNullOrEmpty(employee.LastName))
thrownew ArgumentException("LastName cannot be null or an empty string.");
if (employee.Address == null) { employee.Address = String.Empty; }
if (employee.City == null) { employee.City = String.Empty; }
if (employee.Region == null) { employee.Region = String.Empty; }
if (employee.PostalCode == null) { employee.PostalCode = String.Empty; }
SqlConnection conn = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand("UPDATE Employees " +
" SET FirstName=@FirstName, LastName=@LastName, " +
" Address=@Address, City=@City, Region=@Region, " +
" PostalCode=@PostalCode " +
" WHERE EmployeeID=@EmployeeID", conn);
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 10).Value = employee.FirstName;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 20).Value = employee.LastName;
cmd.Parameters.Add("@Address", SqlDbType.VarChar, 60).Value = employee.Address;
cmd.Parameters.Add("@City", SqlDbType.VarChar, 15).Value = employee.City;
cmd.Parameters.Add("@Region", SqlDbType.VarChar, 15).Value = employee.Region;
cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = employee.PostalCode;
cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = employee.EmployeeID;
int result = 0;
try
{
conn.Open();
result = cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
// Handle exception.
}
finally
{
conn.Close();
}
return result;
}