Tag: c# SQL ADO.NET
C# Determining if a column exists in an SQL database using ADO.Net
by brian on Feb.15, 2008, under c#, coding
This information was very difficult to come by. There isn’t any useful documentation or tutorials that I found. I have to admit that what follows may only be valid for the System.Data.SQLite.SQLiteConnection sql connection. Just as a warning it may or may not work with a different database connection.
The idea is that you’ve changed your database layout and you want test the opened database to make sure the changes are valid. If they aren’t then you want to alter the table. Anyway here is the code
DataTable columns = connection.GetSchema("columns");
System.Data.DataRow[] selColumns = columns.Select("COLUMN_NAME='PREVIEW' AND TABLE_NAME='IMAGES'");
if (selColumns.Length == 0)
{
ExecuteNonQuerySql("ALTER TABLE IMAGES ADD COLUMN PREVIEW BLOB");
}
The following line gets the schema table that holds all of the columns from every table.
DataTable columns = connection.GetSchema("columns");
The following line filters through all of the columns and get’s just the column with name ‘PREVIEW’ and belongs to the table ‘IMAGES’.
System.Data.DataRow[] selColumns = columns.Select("COLUMN_NAME='PREVIEW' AND TABLE_NAME='IMAGES'");
If there are any columns that fit the filter than the length of selColumns will be greater than zero. If it doesn’t exist than selColumns.Length will be 0 and you know that the column doesn’t exist.
