我想知道在.Net中開發CRUD操作(特別是當您使用數據庫作爲數據源時)是否會有任何可信的方法用於try-catch塊的catch部分?.Net:在開發CRUD操作時,您在try-catch塊的「Catch」部分中有什麼自信的方法?
好吧,您對下面的行有什麼看法?
public int Insert(string name, Int32 employeeID, string createDate)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = this._ConnectionString;
try
{
SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UnitInsert";
if (connection.State != ConnectionState.Open)
connection.Open();
SqlCommandBuilder.DeriveParameters(command);
command.Parameters["@Name"].Value = name;
command.Parameters["@EmployeeID"].Value = employeeID;
command.Parameters["@CreateDate"].Value = createDate;
int i = command.ExecuteNonQuery();
command.Dispose();
return i;
}
catch
{
**// how do you "catch" any possible error here?**
return 0;
//
}
finally
{
connection.Close();
connection.Dispose();
connection = null;
}
}
完全在一條切線上,但你應該嘗試使用'using'語句,而不是'try' /'finally'並自己調用'Dispose'。 http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx – 2010-04-29 12:02:42
爲什麼要檢查連接狀態是否打開?它不會打開,所以只需調用'Open'即可。 – 2010-04-29 12:03:59
@Matthew:順便說一句,這是什麼意思:完全切線? – odiseh 2010-04-29 12:37:17