有没有办法使用 ADO.NET 来确定与任何数据提供程序一起使用的数据库中是否存在表?

发布于 2024-09-15 09:23:05 字数 465 浏览 4 评论 0原文

有没有办法使用 ADO.NET 来确定与任何数据提供程序一起使用的数据库中是否存在表?

我目前正在做这样的事情:

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

我希望有一种不涉及捕获异常的方法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

盗梦空间 2024-09-22 09:23:05

那么,您可以使用 Connection.GetSchema("TABLES") 方法。

这将返回一个DataTable,其中包含数据库中所有表的行。从这里您可以检查该表是否存在。

然后可以更进一步:

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

如果您使用 .NET 3.5,那么您也可以将其设为扩展方法。

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.

猫卆 2024-09-22 09:23:05

对凯尔的答案进行了小改进,以考虑不同的数据库(例如 oracle 与 ms-sql-server)将表名列放置在“表”表中的不同索引中:

    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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文