简体   繁体   中英

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 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

With SQLite.net it´s easy to know if a column exists, in case you really need it:

var tableInfo = connection.GetTableInfo("YourTable");
var columnExists = tableInfo.Any(x => x.Name.Equals("ColumnName"));

But as mentioned before, connection.CreateTable<T>() or connection.CreateTableAsync<T>() will add the new columns for you, so you don´t need to execute sql statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM