gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:51:51 32 4
gpt4 key购买 nike

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
}

关于c# - 检查表是否存在 : Table doesn't exist while it exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14134688/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com