C# 使用命令检查表是否存在

C# 使用命令检查表是否存在,c#,sql-server,C#,Sql Server,我正在尝试编写一个方法来检查表是否存在。我试图使用using语句在数据库中保持一致 public void checkTableExists() { connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\keith_000\Documents\ZuriRubberDressDB.mdf;Integrated Security=True;Connect Timeout=30";

我正在尝试编写一个方法来检查表是否存在。我试图使用using语句在数据库中保持一致

public void checkTableExists()
{
    connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\keith_000\Documents\ZuriRubberDressDB.mdf;Integrated Security=True;Connect Timeout=30";

    string tblnm = "BasicHours";
    string str = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = " + tblnm + ");";

    SqlDataReader myReader = null;
    int count = 0;

    try
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(str, connection))
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    MessageBox.Show("The count is " + count);

                    myReader = command.ExecuteReader();

                    while (myReader.Read())
                    {
                        count++;
                    }

                    myReader.Close();

                    MessageBox.Show("Table Exists!");
                    MessageBox.Show("The count is " + count);
                }

                connection.Close();
            }
        }
    }
    catch (SqlException ex)
    {
        MessageBox.Show("Sql issue");
    }
    catch (Exception ex)
    {
        MessageBox.Show("Major issue");
    }

    if (count > 0)
    {
        MessageBox.Show("Table exists");
    }
    else
    {
        MessageBox.Show("Table doesn't exists");
    }
}
它在命中try块时抛出异常。它捕获
SqlException

这就是我再次学习与数据库交互的地方。解决方案是好的,但更重要的是,简要说明我需要在哪里学习如何改进代码

谢谢


Keith

我在我的项目中使用了以下代码,并为我工作:

 try
 {
     using (con = new SqlConnection(Constr);)
        {
            con.Open();
            string query = $"IF EXISTS (SELECT * FROM sys.tables WHERE name = '{tableName}') SELECT 1 ELSE Select 0;"
             Exists = int.Parse(sqlQuery.ExecuteScalar().ToString())==1;
             con.Close();
         }

  }
  catch{}

问题可能是这样一行:
string tblnm=“BasicHours”。如果表名是一个字符串,应该加撇号,请尝试以下操作:
string tblnm=“'BasicHours'”


在catch块中,您还可以记录异常消息和详细信息。

您的代码失败,因为当您直接编写搜索字符串值的查询时,该值应包含在单引号中,如“BasicHours”

但是,您的实际代码还有一些改进。
首先,您可以使用简化的sql命令。
其次,使用参数而不是字符串连接

SqlCommand cmd = new SqlCommand(@"IF EXISTS(
  SELECT 1 FROM INFORMATION_SCHEMA.TABLES 
  WHERE TABLE_NAME = @table) 
  SELECT 1 ELSE SELECT 0", connection);

cmd.Parameters.Add("@table", SqlDbType.NVarChar).Value = tblName;
int exists = (int)cmd.ExecuteScalar();
if(exists == 1)
    // Table exists
此命令文本不要求您使用SqlDataReader,因为查询只返回一行和一列,并且单个单元格的值为1或0。
开销少了很多

其中最重要的一点是,您永远不会构建连接字符串的sql查询。众所周知,这种方法会引起问题。
更糟糕的情况可能会破坏您的数据库或向黑客泄露机密信息。当连接的字符串包含单引号时,次要的是崩溃。始终使用参数化查询

感谢您在这个问题上的帮助。这就是我正在实施的解决方案

    public void checkTableExists()
    {
        connectionString = @" 
        Data Source=(LocalDB)\MSSQLLocalDB;
        AttachDbFilename=C:\Users\keith_000\Documents\ZuriRubberDressDB.mdf;
        Integrated Security=True;
        Connect Timeout=30";

        string tblName = @"BasicHours";
        string str = @"IF EXISTS(
                SELECT 1 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_NAME = @table) 
                SELECT 1 ELSE SELECT 0";

        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand(str, connection))
                {
                    connection.Open();
                    SqlCommand cmd = new SqlCommand(str, connection);

                    cmd.Parameters.Add("@table", SqlDbType.NVarChar).Value = tblName;
                    int exists = (int)cmd.ExecuteScalar();
                    if (exists == 1)
                    {
                        MessageBox.Show("Table exists");
                    }
                    else
                    {
                        MessageBox.Show("Table doesn't exists");
                    }
                    connection.Close();
                }
            }
        }
        catch (SqlException ex)
        {
            MessageBox.Show("Sql issue");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Major issue");
        }
    }

表名称是一个字符串字段。在变量周围需要单引号,但最好使用参数请不要这样连接SQL查询。(tblnm=“BasicHours;TRUNCATE TABLE[BasicHours];”改为使用参数化的SqlCommand对象。您会遇到什么异常?