Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an way using ADO.NET to determine if a table exists in a database that works with any data provider?

Tags:

c#

sql

ado.net

Is there an way using ADO.NET to determine if a table exists in a database that works with any data provider?

I'm currently doing something like this:

bool DoesTableExist(string tableName)
{
    DbCommand command = this.dbConnection.CreateCommand();
    command.CommandText = "SELECT 1 FROM " + tableName;
    try
    {
        using (DbDataReader reader = command.ExecuteReader())
        {
            return true;
        }
    }
    catch (DbException)
    {
        return false;
    }
}

I'm hoping that there is a way that doesn't involve catching exceptions.

like image 835
Ergwun Avatar asked Aug 20 '10 05:08

Ergwun


People also ask

How do you check table is exists or not?

To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID(). The INFORMATION_SCHEMA. TABLES returns one row for each table in the current database.

How do you check if table is exists in SQL?

To check if a table exists in SQL Server, you can use the INFORMATION_SCHEMA. TABLES table. You can use this table with an IF THEN clause do determine how your query responds whether or not a table exists.

How does ADO.NET connect to database?

Establish Connection to DatabaseBrowse your database file and click the OK button. After connecting to the new database file create an object of OleDBConnection class in case of a database like Oracle or MS-Access and create an object of SqlConnection class in case of MS-SQL database.


1 Answers

Well, you can use the Connection.GetSchema("TABLES") method.

This returns a DataTable which will contains rows of all the tables in your DB. From here you can check against this and see if the table exists.

This can then be taken a step further:

    private static bool DoesTableExist(string TableName)
    {
        using (SqlConnection conn = 
                     new SqlConnection("Data Source=DBServer;Initial Catalog=InitialDB;User Id=uname;Password=pword;"))
        {
            conn.Open();

            DataTable dTable = conn.GetSchema("TABLES", 
                           new string[] { null, null, "MyTableName" });

            return dTable.Rows.Count > 0;
        }
    }

If you're using .NET 3.5, then you can make this an extension method as well.

like image 135
Kyle Rosendo Avatar answered Oct 11 '22 14:10

Kyle Rosendo