在我的代码上使用“使用”的正确方法

时间:2013-11-24 03:08:02

标签: c# using

我只是想知道我在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”。

1 个答案:

答案 0 :(得分:5)

这是一种“腰带和吊带”的方法:您应该使用usingfinally,而不是两者。

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.
            }
        }
}