Pergunta

I just want to know if I did the right way in using the "using" in my CRUDStudentTable().

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

If this is not right, kindly give me an advice on how to do this right. Thank you.

I included here another method that return the "message" whenever it is not null.

Foi útil?

Solução

This is a kind of "belt and suspenders" approach: you should use either a using or a finally, but not both.

The using block guarantees to close your connection in all code paths, including the ones with exceptions. Therefore you can rewrite the code as follows:

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.
            }
        }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top