【问题标题】:Check if table exists using command使用命令检查表是否存在
【发布时间】:2017-03-18 03:21:06
【问题描述】:

我正在尝试编写一种方法来检查表是否存在。我正在尝试使用 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 块中捕获。

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

谢谢

基思

【问题讨论】:

  • TABLE_NAME 是一个字符串字段。您需要在变量周围加上单引号,但最好使用参数
  • 请不要像这样连接 SQL 查询。 (tblnm = "BasicHours; TRUNCATE TABLE [BasicHours];" 改用参数化 SqlCommand 对象。
  • 你遇到了什么异常?

标签: c# sql-server


【解决方案1】:

您的代码会失败,因为当您直接编写一个搜索字符串值的查询时,该值应该用单引号括起来,例如“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 查询。众所周知,这种方法会导致问题。 更糟糕的是称为SQL Injection,它可能会破坏您的数据库或向黑客泄露机密信息。当连接的字符串包含单引号时,次要的崩溃。始终使用参数化查询。

【讨论】:

    【解决方案2】:

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

     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{}
    

    【讨论】:

      【解决方案3】:

      问题可能出在以下行:string tblnm = "BasicHours";。你的表名是一个字符串,应该用撇号,试试这个:string tblnm = "'BasicHours'";

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

      【讨论】:

        【解决方案4】:

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

            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");
                }
            }
        

        【讨论】:

          猜你喜欢
          • 2015-04-07
          • 1970-01-01
          • 1970-01-01
          • 2018-12-25
          • 2016-04-15
          • 2011-11-05
          • 1970-01-01
          • 2022-11-23
          • 2016-04-29
          相关资源
          最近更新 更多