我只是想知道我在CRUDStudentTable()中使用“using”是否正确。
private string Query;
public string message;
public CRUD(string myQuery)
{
Query = myQuery;
}
public void CRUDStudentTable()
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Microsoft User\Desktop\Student.accdb"))
{
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(Query, conn))
{
cmd.ExecuteNonQuery();
}
}
catch (Exception exception)
{
message = exception.Message;
}
finally
{
conn.Close();
}
}
}
public string HasError()
{
if (string.IsNullOrEmpty(message))
{
message = "Successful";
return message;
}
else
{
return message;
}
}
如果这不对,请告诉我如何正确行事。谢谢。
我在这里包含了另一个方法,只要它不为空,就会返回“message”。
答案 0 :(得分:5)
这是一种“腰带和吊带”的方法:您应该使用using
或finally
,而不是两者。
using
块保证在所有代码路径中关闭连接,包括具有异常的路径。因此,您可以按如下方式重写代码:
public void CRUDStudentTable()
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Microsoft User\Desktop\Student.accdb"))
{
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(Query, conn))
{
cmd.ExecuteNonQuery();
}
}
catch (Exception exception)
{
message = exception.Message;
// Consider re-throwing the exception here
// to let callers know what happened.
// Silently harvesting the message and continuing
// is not a good practice of handling exceptions.
}
}
}