uso son que principales net metodo los ejemplo cuáles conforman c# sql ado.net

c# - son - ¿Hay alguna manera de usar ADO.NET para determinar si existe una tabla en una base de datos que funcione con cualquier proveedor de datos?



metodo fill dataadapter (2)

¿Hay alguna manera de usar ADO.NET para determinar si existe una tabla en una base de datos que funcione con cualquier proveedor de datos?

Actualmente estoy haciendo algo como esto:

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; } }

Espero que haya una forma que no implique atrapar excepciones.


Pequeña mejora en la respuesta de Kyle para tener en cuenta el hecho de que diferentes bases de datos (oracle vs ms-sql-server por ejemplo) colocan la columna de nombre de tabla en un índice diferente en la tabla "Tablas":

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


Bueno, puedes usar el método Connection.GetSchema("TABLES") .

Esto devuelve una DataTable que contendrá filas de todas las tablas en su DB. Desde aquí puedes verificar esto y ver si la tabla existe.

Esto puede tomarse un paso más:

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; } }

Si está utilizando .NET 3.5, también puede hacer que este sea un método de extensión.