Bee Eee Blog

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.

:
1 comment for this entry:
  1. CLAUDE


    CheapTabletsOnline.Com. Canadian Health&Care.Best quality drugs.Special Internet Prices.No prescription online pharmacy. High quality drugs. Buy pills online

    Buy:Viagra Super Active+.Cialis Professional.Viagra.Cialis Super Active+.Soma.Tramadol.Super Active ED Pack.Maxaman.Zithromax.Propecia.Levitra.Cialis Soft Tabs.Viagra Professional.Cialis.Viagra Soft Tabs.VPXL.Viagra Super Force….

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...