Search code examples
c#sqlitewindows-runtimesqlite.net

SQLite.NET Check if column exists in table


I have created following method that Adds a column in an already existing SQLite table

public async void AddColumnMyNewColumn()
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection(path);
    await conn.ExecuteAsync("ALTER TABLE MyTable ADD COLUMN MyNewColumn bit DEFAULT 'False';");
}

It creates a new column MyNewColumn in MyTable.

Next time when AddColumnMyNewColumn method is called, then it throws an error.

How to check if this column is already created??

I've cheched this,and this, but I cant put these things together to get something like this..

public async void AddColumnMyNewColumn()
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection(path);
    bool columnExists;

    //Check if column exists & set columnExists accordingly

    if(!columnExists)
        await conn.ExecuteAsync("ALTER TABLE MyTable ADD COLUMN MyNewColumn bit DEFAULT 'False';");
}

Solution

  • Solution 1. Using SQLite.Net

    You are using SQLite.Net, so your Tables are mapped to C# Classes, right?

    And if you add a Property to your C# Class you can just call this

    SQLiteAsyncConnection conn = new SQLiteAsyncConnection(path); 
    
    await conn.CreateTableAsync<MyTableClass>();
    

    and your new property will be added as a column to your Table, all previous data will not be changed

    Solution 2. Using a query

    (to list all columns of a table) and then you could add your column manually)

    SQLite Schema Information Metadata