【问题标题】:SQL Check if table Exists in C#, if not createSQL 检查表是否存在于 C# 中,如果不创建
【发布时间】:2014-04-14 17:36:16
【问题描述】:

我想我几乎看过与这个问题相关的每一页,最有可能的答案是 Check if a SQL table exists 但并没有真正理解它。这是我得到的:

    private void select_btn_Click(object sender, EventArgs e)
    {
        string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");
        SqlConnection SC = new SqlConnection("Data Source=ruudpc;Initial Catalog=leden;Integrated Security=True");
        SqlCommand DateCheck = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + theDate + "'");
    }

现在我想要 DateCheck.ExecuteScalar(); 的返回值;这可以告诉我它是否存在,可能很简单。

编辑

不管 sql 注入部分,对于某些人来说这个问题是有帮助的,动态创建表通常是不好的做法,我建议你重新考虑你的 ERD。只是说说而已。

【问题讨论】:

  • 不要为此连接 sql。使用参数化sql,防止sql注入。

标签: c# sql sql-server sqlcommand information-schema


【解决方案1】:

使用 IF EXISTS T-SQL

private void select_btn_Click(object sender, EventArgs e)
{
    string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");

    // Enclose the connection inside a using statement to close and dispose
    // when you don't need anymore the connection (to free local and server resources)
    using(SqlConnection SC = new SqlConnection("Data Source=ruudpc;Initial Catalog=leden;Integrated Security=True"))
    {
        // Sql command with parameter 
        string cmdText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES 
                           WHERE TABLE_NAME=@name) SELECT 1 ELSE SELECT 0";
        SC.Open();
        SqlCommand DateCheck = new SqlCommand(cmdText, SC);

        // Add the parameter value to the command parameters collection
        DateCheck.Parameters.Add("@name", SqlDbType.NVarChar).Value = theDate

        // IF EXISTS returns the SELECT 1 if the table exists or SELECT 0 if not
        int x = Convert.ToInt32(DateCheck.ExecuteScalar());
        if (x == 1)
            MessageBox.Show("Table exists for date " + theDate);
        else
            MessageBox.Show("Table doesn't exist for date " + theDate);
    }
}

【讨论】:

    【解决方案2】:

    你编写代码的方式可能会导致sql注入攻击。参数化的SQL语句是一种避免SQL注入攻击的简单方法,也是一种很好的编码实践

    CREATE PROCEDURE checkTableExist
    @theDate  varchar(10)
    AS 
    SET NOCOUNT ON;
    IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=@theDate) SELECT 1     ELSE SELECT 0
    

    C#代码

      try
      {     
         string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");    
         sqlConnection = new SqlConnection(dbConnectionString);
         SqlCommand command = new SqlCommand("checkTableExist", sqlConnection);
         command.CommandType = CommandType.StoredProcedure;
         command.Parameters.Add("@theDate", SqlDbType.VarChar).Value = dateTimePicker1.Value.ToString("dd-MM-yyyy");
         sqlConnection.Open();
         int result = (Int32)command.ExecuteScalar();
         sqlConnection.Close();
    
         if (result == 1)
         return true;//or any message 
         else
         return false;    
      }
    catch (SqlException ex)
      {
         Console.WriteLine("SQL Error" + ex.Message.ToString());
         return false;
      }
    

    【讨论】:

    • 赞成,您的回答修复了一个我忘记在回答中解决的明显错误。
    猜你喜欢
    • 2011-08-22
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2014-07-23
    • 2011-05-12
    相关资源
    最近更新 更多