Search code examples
c#ms-accessexceptiontry-catchnullreferenceexception

Check for the existence of a record in Access database using C#


First, I did search for this first and found this question answered: Previous Answer

The problem I have with this answer is that using this method causes a NullReferenceException. Obviously the code will still work with a try/catch block, but I had always understood that intentionally using an Exception as a means of controlling flow was poor design. Is there a better method of doing this?

To be clear as to the parameters, I am using OleDbConnection and OleDbCommand to read/write an Access 2010 database (.accdb format).

Below is the code I have currently using the above answer's approach:

public bool ReadAccessDb(string filePath, string queryString, bool hasRecords)
    {
        string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
            @"Data Source=" + filePath + ";" +
            @"User Id=;Password=;";

        using (OleDbConnection connection = new OleDbConnection(connectionString))
        using (OleDbCommand command = new OleDbCommand(queryString, connection))
        {
            try
            {
                connection.Open();

                int count = (int)command.ExecuteScalar();

                //This works, but if no records exist it uses the Exception system to halt further action.  Look for better approach.
                if(count > 0)
                {
                    hasRecords = true;
                }
            }
            catch (System.Exception ex)
            {
            }
        }

        return hasRecords;
    }

Solution

  • You can use :

    int count = command.ExecuteScalar() is DBNull ? 0 : Convert.ToInt32(command.ExecuteScalar());
    

    or use :

    object obj = command.ExecuteScalar();
    int count = obj is DBNull ? 0 : Convert.ToInt32(obj);