有没有办法使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望有一种方法不涉及捕获异常.
Kyl*_*ndo 19
好吧,你可以使用这个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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是.NET 3.5,那么您也可以将其作为扩展方法.
| 归档时间: |
|
| 查看次数: |
4320 次 |
| 最近记录: |