Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite ExecuteScalar throwing NullReferenceExcpetion

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

like image 206
Chase Florell Avatar asked Feb 15 '23 23:02

Chase Florell


1 Answers

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;

        }
    }
}
like image 190
Chase Florell Avatar answered Feb 24 '23 15:02

Chase Florell