Home > front end >  SqliteCommand.ExecuteScalar() returns null (C# 5.0 and System.Data.Sqlite)
SqliteCommand.ExecuteScalar() returns null (C# 5.0 and System.Data.Sqlite)

Time:10-06

This code works!!!

DB path was wrong. Because of this, when I was executing:

dbConnection.Open();

Instead of opening my DB, I was creating an empty one.

Thank you all for your help!


The problem

I am using C#.NET 5.0 and System.Data.Sqlite to create a console application that runs on windows.

I am trying to check if a table called "parcelas" exist on the database For that I am using this query:

SELECT name FROM sqlite_master WHERE type='table' AND name='parcelas'

This query runs with no problems on DB Browser. But when I run it on my C# program the query returns "null" without any exceptions (for sure I have one "System.NullReferenceException" when trying to read the null result)

I tried casting the result object and calling .toString() without success.

¿Am I doing something wrong?

Here is the code:

public void TableExist(string tableName)
    {
        if (tableName == null || db == null || db.State != System.Data.ConnectionState.Open)
        {
            Console.WriteLine("ERROR!!!");
            return;
        }

        SQLiteCommand cmd = new SQLiteCommand(db);
        cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='"  tableName  "'";
        var result = cmd.ExecuteScalar();
        Console.WriteLine("RESULT: "   result.ToString());
        return;

    }

CodePudding user response:

ExecuteScalar returns null when zero rows are returned from a query; it returns DBNull.Value when at least one row is returned and the value in the first column is a database null.

So: your query is not returning rows. Check whether that is expected, and if not: fix it. I would, however, be much more concerned about the SQL injection vulnerability in AND name='" tableName "'";; parameters should always be preferred.

  • Related