user1462199
user1462199

Reputation:

SQLite Stores characters as strings?

I am using the System.Data.SQLite ADO.Net Provider to interact with an SQLite DB. I used the following syntax to create a new table:

CREATE TABLE [tb_Replace] ([Character] CHAR(1), [Substitute] CHAR(1))

I then tried to read the data using a simple select:

public static List<char> GetReplaceableCharacters(string connectionString)
{
    List<char> replaceableCharacters = new List<char>();
    SQLiteConnection sqlConnection = new SQLiteConnection(connectionString);
    sqlConnection.Open();
    using (SQLiteTransaction transaction = sqlConnection.BeginTransaction())
    {
        SQLiteCommand command = new SQLiteCommand(@"SELECT Character FROM tb_Replace", sqlConnection);
        SQLiteDataReader reader = command.ExecuteReader();
        while (reader.Read())
            replaceableCharacters.Add((char)reader["Character"]);
    }
    sqlConnection.Close();
    return replaceableCharacters;
}

However when I did that it threw an InvalidCastException. However, if I change the return type to aList<string> and cast reader["Character"] to a string it works. Does anyone know why this would be?

Upvotes: 3

Views: 1059

Answers (1)

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

Just read http://www.sqlite.org/datatype3.html.

Sqlite has five type affinities (types preferred by a column of a table) and five storage classes (possible actual value types). There is no CHARACTER type among either of them.

Sqlite allows you to specify just about anything as a type for column creation. But it doesn't enforce types for everything except INTEGER PRIMARY KEY columns. It recognizes a few substring of declared type names to determine column type affinity, so CHARACTER, CHARCOAL and CONTEXTUALIZABLE are all just a funny way of writing TEXT.

Upvotes: 4

Related Questions