Skip to main content
 首页 » 编程设计

c#之检查表是否存在 : Table doesn't exist while it exists

2024年02月20日13lhb25

public bool CheckTblExist(string TblName) 
    { 
        try 
        {   
            string cmTxt = "select case when exists"  
            + "((select * from information_schema.tables "  
            + "where table_name = '" + TblName + "')) then 1 else 0 end"; 
 
            var cmd = new OdbcCommand(cmTxt); 
            if ((int)cmd.ExecuteScalar() == 1) exists = true; 
            MessageBox.Show(TblName + " table Exists."); 
        } 
        catch 
        { 
            exists = false; 
            MessageBox.Show(TblName + " table does not Exist."); 
        } 
        return exists; 
    } 

我使用 VS2012、C# 在 App_Data 中手动创建了名为 Tasoo1.mdf 的 mdf 文件,连接名为 con。 Tasoo.mdf 已使用

创建了 1 个名为“1010”的表
string cmdText = "CREATE TABLE [" + tblname + "]"  
                 + "(column_name1 int,column_name2 int,column_name3 int)"; 

执行代码,给我的表不存在?知道如何解决这个问题..非常感谢。

请您参考如下方法:

您的 if 语句下只有一个语句,即 exists = true。您的 MessageBox.Show 在 if 语句之外。因此,即使 if 语句返回 false,您也始终会得到该表存在的消息。将其包含在 {} 中。

if ((int)cmd.ExecuteScalar() == 1)  
{     
     exists = true; 
     MessageBox.Show(TblName + " table Exists."); 
} 

您当前的代码:

if ((int)cmd.ExecuteScalar() == 1) exists = true; 
MessageBox.Show(TblName + " table Exists."); // this is irrespective of the if  

Excauting the code, gave me- table doesn't exist?

您在您的 catch block 中展示了这一点。这意味着你得到了一些异常(exception)。有一个空的 catch block 不是一个好主意。捕获异常并查看出了什么问题。

catch(SqlException ex) 
{ 
   MessageBox.Show(ex.Message); 
   //handle exception 
}