这个查询:
string.Format("SELECT COUNT(*) FROM {0}", tableName);
...我将其用作“isValidTable(string tableName)”方法的核心,如果 tableName 不存在(具体来说,“指定的表不存在”)则抛出异常。
既然如此(它玩起来不好,如果它不识别表名就会举手)让我想知道这段代码是否:
public bool isValidTable(string tableName)
{
bool validTable = false;
string tblQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
try
{
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandText = tblQuery;
object objcnt = cmd.ExecuteScalar();
if ((objcnt != null) && (objcnt != DBNull.Value))
{
validTable = Int32.Parse(objcnt.ToString()) > 0;
}
else
{
MessageBox.Show("NULL returned from isValidTable(). Remove this line."); //<- I never see this; if this is the case, an exception has been thrown
}
}
catch
{
return false;
}
return validTable;
}
...可以/应该简化为:
public bool isValidTable(string tableName)
{
string tblQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
try
{
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandText = tblQuery;
cmd.ExecuteScalar();
}
catch
{
return false;
}
return true;
}
?
更新
jp2code 认为:“存在时选择大小写((select * from information_schema.tables where table_name = '{0}'))然后 1 else 0 end”
是否有类似的代码来检查列是否存在?目前我的 isValidTable() 和 isValidColumn() 查询是相似的:
string tableQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
string columnQuery = string.Format("SELECT COUNT({0}) FROM {1}", columnName, tableName);
...但是如果我能够将它用于 isValidTable():
string.Format("select case when exists((select * from information_schema.tables where table_name = '{0}')) then 1 else 0 end",
tableName);
...还有我可以用来检查有效列的扩展吗?像这样的东西:
string.Format("select case when exists((select * from information_schema.tables where table_name = '{0}' and column_name = '{1}')) then 1 else 0 end",
tableName, columnName);
???
更新 2
我意识到建议的 sql 比“我的方式”“更好”,但无论出于何种原因,当我使用“首选方法”时,所需的数据表未被识别为存在(尽管,当然,它们确实存在)。要么我使用的旧版软件不接受嵌套选择/子选择,要么...???
无论如何,评论讲述了这个故事:
string tblQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
// This is doubtless "more better," but when I use it, I get "No current work; no inventory file"
//string tblQuery = string.Format("select case when exists((select * from information_schema.tables where table_name = '{0}')) then 1 else 0 end", tableName);
最佳答案
您应该只对异常(超出规范)的事情使用异常,找不到表被认为是该方法的正常执行,因此不应依赖异常的发生。
对于您的示例来说,不正常的事情是连接超时,这不是您的方法的标准操作。
相反,您应该查询 sys.tables
或 INFORMATION_SCHEMA.TABLES
表以查看您的表是否存在。
关于c# - 依赖失败尝试的异常是返回 bool 值的可接受方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774160/