Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for MS Access database table if not exist create it

Tags:

c#

ms-access

How do you programmatically check for MS Access database table, if not exist then create it?

like image 499
LEMUEL ADANE Avatar asked Jan 25 '11 12:01

LEMUEL ADANE


People also ask

What happens if you create a table that already exists?

Answer. When you try to create a table with an already existing table name, you will receive an error message, and no table will be modified or created.

How do you find blanks in access?

Find blank values. As needed, open the table in Datasheet view that contains the values you want to find. In the table, select the field that contains the blank values that you want to find. On the Home tab, in the Find group, click Find, or press CTRL+F.


2 Answers

To check if a table exists you can extend DbConnection like this:

public static class DbConnectionExtensions
{
    public static bool TableExists(this DbConnection conn, string table)
    {
        conn.open();
        var exists = conn.GetSchema("Tables", new string[4] { null, null, table, "TABLE" }).Rows.Count > 0;
        conn.close();
        return exists;
    }
}

Then you can call TableExists in any derived class like OleDbConnection, SQLiteConnection or SqlConnection.

like image 41
csname1910 Avatar answered Oct 06 '22 00:10

csname1910


You could iterate though the table names to check for a specific table. See the below code to get the table names.

        string connectionstring = "Your connection string";
        string[] restrictionValues = new string[4]{null,null,null,"TABLE"};
        OleDbConnection oleDbCon = new OleDbConnection(connectionString);
        List<string> tableNames = new List<string>();

        try
        {
            oleDbCon.Open();
            DataTable schemaInformation = oleDbCon.GetSchema("Tables", restrictionValues);

            foreach (DataRow row in schemaInformation.Rows)
            {
               tableNames.Add(row.ItemArray[2].ToString());
            }
        }
        finally
        {
            oleDbCon.Close();
        }           
like image 144
Stephen Dryden Avatar answered Oct 05 '22 22:10

Stephen Dryden