Is there an way using ADO.NET to determine if a table exists in a database that works with any data provider?
Is there an way using ADO.NET to determine if a table exists in a database t开发者_如何转开发hat 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.
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.
Small improvement on Kyle's answer to account for the fact that different databases (oracle vs ms-sql-server for instance) place the table-name column in a different index in the "Tables" table:
public static bool CheckIfTableExists(this DbConnection connection, string tableName) //connection = ((DbContext) _context).Database.Connection;
{
if (connection == null)
throw new ArgumentException(nameof(connection));
if (connection.State == ConnectionState.Closed)
connection.Open();
var tableInfoOnTables = connection //0
.GetSchema("Tables")
.Columns
.Cast<DataColumn>()
.Select(x => x.ColumnName?.ToLowerInvariant() ?? "")
.ToList();
var tableNameColumnIndex = tableInfoOnTables.FindIndex(x => x.Contains("table".ToLowerInvariant()) && x.Contains("name".ToLowerInvariant())); //order
tableNameColumnIndex = tableNameColumnIndex == -1 ? tableInfoOnTables.FindIndex(x => x.Contains("table".ToLowerInvariant())) : tableNameColumnIndex; //order
tableNameColumnIndex = tableNameColumnIndex == -1 ? tableInfoOnTables.FindIndex(x => x.Contains("name".ToLowerInvariant())) : tableNameColumnIndex; //order
if (tableNameColumnIndex == -1)
throw new ApplicationException("Failed to spot which column holds the names of the tables in the dictionary-table of the DB");
var constraints = new string[tableNameColumnIndex + 1];
constraints[tableNameColumnIndex] = tableName;
return connection.GetSchema("Tables", constraints)?.Rows.Count > 0;
}
//0 different databases have different number of columns and different names assigned to them
//
// SCHEMA,TABLENAME,TYPE -> oracle
// table_catalog,table_schema,table_name,table_type -> mssqlserver
//
// we thus need to figure out which column represents the tablename and target that one
精彩评论