Home » c# » c# – How can I get data from a Select query as a String data type from a SQLite database?

c# – How can I get data from a Select query as a String data type from a SQLite database?

Posted by: admin February 21, 2020 Leave a comment

Questions:

I’m using this query:

string query = "SELECT CAST(FullName AS STRING) FROM Register WHERE ID = 1;

DataTable result = SQLiteDataAccess.MakeQuery(query);

from this SQLite Table. I’m using System.Data and Dapper to access the SQLite database. The following code is used to access the database:

public static DataTable MakeQuery(string query)
{
            SQLiteDataReader result;
            DataTable datatable = new DataTable();

        using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
        {
            cnn.Open();

            SQLiteCommand command = new SQLiteCommand(query, cnn);
            result = command.ExecuteReader();
            datatable.Load(result);

            cnn.Close();
        }

        return datatable;
    }

When I try to use the result, for example with this code:

        foreach (DataRow record in result.Rows)
        {
            names.Add((string)record["FullName"]);
        }

I get the error “System.ArgumentException: ‘Column ‘FullName’ does not belong to table .'” The following locals window screenshot shows that the name of the column is “CAST(FullName AS STRING)” and not “FullName”, and the data type is int64, not string.

It seems that I’m using the wrong syntax for casting data types. It must be different in SQLite because it works in SQL Server. What’s the correct query in SQLite? Thanks

Edit: Tried a suggestion in a comment and got this error showing the data type is still Int64.

How to&Answers:

I don’t see the point for casting, since your data seems to be stored in a string-like datatype already. So why not just do:

SELECT FullName FROM Register WHERE ID = 1;

If, for some reason, you do nee to cast, then you would need to alias the expression, so you can later on access it from your code:

SELECT CAST(FullName AS TEXT) FullName FROM Register WHERE ID = 1;

###

If you don’t define the name of a requested column, your database has to go with some kind of default. Normally, this is the name of your column. If you start throwing functions around though, things get much more complicated for such an idea. After all, you could include two columns in the function.

Luckily this is very easily fixed using the AS keyword. Change your query to:

string query = "SELECT CAST(FullName AS TEXT) as FullName FROM Register WHERE ID = 1;

Note: I chose to use FullName here, as you seem to want to. This is fine as long as you don’t duplicate column names in the call.

I’ve also changed the STRING type to TEXT since that’s sqlite3’s actual type.