Sqlite ExecuteScalar throwing NullReferenceExcpetion

Chase Florell picture Chase Florell · Oct 17, 2013 · Viewed 7.3k times · Source

I have a custom written DB provider. When I run my tests, they're breaking on the ExecuteScalar command with a NullReferenceException. What might I be missing here? I've read that some people have a MultiThreading issue, but I don't "think" that's what I'm running into.

Here's my GetOpenConnection method

public SqliteConnection GetOpenConnection()
{
    var connection = new SqliteConnection(_connectionString);
    if (connection == null) throw new Exception("Could not create a database connection.");

    connection.Open();

    return connection;
}

And the ExecuteScalar method

public TKey ExecuteScalar<TKey> ( string commandText, IDictionary<string, object> parameters )
{
    using ( var connection = _connectionProvider.GetOpenConnection() )
    {
        using ( var command = connection.CreateCommand() )
        {
            command.CommandType = CommandType.Text;
            command.CommandText = commandText;
            foreach ( var parameter in parameters )
            {
                command.Parameters.Add( new SqliteParameter( parameter.Key, parameter.Value ?? DBNull.Value ) );
            }

            // BREAKING HERE
            return ( TKey )command.ExecuteScalar();
        }
    }
}

And this is the method that's calling the ExecuteScalar

private const string CheckTableExists = "SELECT name FROM sqlite_master WHERE type='table' AND name='{0}'";

public bool CheckIfTableExists ( string tableName )
{
    var exists = ExecuteScalar<int>( string.Format( CheckTableExists, tableName ) ) == 1;
    return exists;
}

I put a break point on it, and try to step into it.. .and the code just breaks and throws the exception... I can't track it down

Answer

Chase Florell picture Chase Florell · Oct 17, 2013

ExecuteScalar returns null if no records were returned by the query. This seems to resolve the NullReferenceException.

public TKey ExecuteScalar<TKey> ( string commandText, IDictionary<string, object> parameters )
{
    using ( var connection = _connectionProvider.GetOpenConnection() )
    {
        using ( var command = connection.CreateCommand() )
        {
            command.CommandType = CommandType.Text;
            command.CommandText = commandText;
            foreach ( var parameter in parameters )
            {
                command.Parameters.Add( new SqliteParameter( parameter.Key, parameter.Value ?? DBNull.Value ) );
            }

            if (typeof (TKey) != typeof (int))
            {
                return (TKey) command.ExecuteScalar();
            }

                var executeScalar = command.ExecuteScalar();
                var item = executeScalar == null ? 0 : 1;
                return (TKey)(object)item;

        }
    }
}