我正在尝试检查 Microsoft SQL Server 中是否存在表,但不知何故,我使用的函数总是返回它不存在,并且输出未指定引发异常。
这发生在我创建表之前(这是预期的),以及在我创建表之后(这不是预期的)。
这是我正在使用的功能:
/// <summary>
/// Checks if a certain Sql Server Table exists
/// </summary>
/// <param name="_databasename">The name of the database</param>
/// <param name="_password">The password of the database</param>
/// <param name="_tablename">The name of the table to check</param>
/// <returns>
/// 'true' if table exists
/// 'false' if table not exists or if an exception was thrown
/// </returns>
public Boolean TableExists(String _databasename, String _password, String _tablename)
{
if (!_databasename.Contains(".sdf")) { _databasename = _databasename + ".sdf"; }
try
{
String connectionString = "DataSource=" + _databasename + "; Password=" + _password;
SqlCeConnection conn = new SqlCeConnection(connectionString);
if (conn.State==ConnectionState.Closed) { conn.Open(); }
using (SqlCeCommand command = conn.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM Information_Schema.Tables WHERE TABLE_NAME = '" + _tablename + "'";
Int32 count = Convert.ToInt32(command.ExecuteScalar());
if (count == 0)
{
Debug.WriteLine("Table " + _tablename + " does not exist.");
return false;
}
else
{
Debug.WriteLine("Table " + _tablename + " exists.");
return true;
}
}
}
catch(Exception _ex)
{
Debug.WriteLine("Failed to determine if table " + _tablename + " exists: " + _ex.Message);
return false;
}
}
显然我在这里缺少一些东西,但我似乎无法找出那是什么。