【问题标题】:How do I re-write a SQL query as a parameterized query?如何将 SQL 查询重写为参数化查询?
【发布时间】:2015-05-01 15:26:43
【问题描述】:

听说用参数化查询可以防止SQL注入攻击,但是不知道怎么写。

如何将以下内容编写为参数化查询?

SqlConnection con = new SqlConnection(
    "Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;" + 
    "Database=ha;" + 
    "Persist Security Info=false;" + 
    "UID='" + globalvariables.user + "';" + 
    "PWD='" + globalvariables.psw + "'");

string query = "SELECT distinct ha FROM app WHERE 1+1=2";

if (comboBox1.Text != "")
{
    query += " AND firma = '" + comboBox1.Text + "'";
}

if (comboBox2.Text != "")
{
    query += " AND type = '" + comboBox2.Text + "'";
}

if (comboBox3.Text != "")
{
    query += " AND farve = '" + comboBox3.Text + "'";
}

SqlCommand mySqlCmd = con.CreateCommand();
mySqlCmd.CommandText = query;

con.Open();
…

【问题讨论】:

    标签: c# .net ado.net sql-injection parameterized-query


    【解决方案1】:

    您需要使用参数,而不是仅仅将您的 SQL 连接在一起:

    using (SqlConnection con = new SqlConnection(--your-connection-string--))
    using (SqlCommand cmd = new SqlCommand(con))
    {
        string query = "SELECT distinct ha FROM app WHERE 1+1=2";
    
        if (comboBox1.Text != "")
        {
            // add an expression with a parameter
            query += " AND firma = @value1 ";
    
            // add parameter and value to the SqlCommand
            cmd.Parameters.Add("@value1", SqlDbType.VarChar, 100).Value = comboBox1.Text; 
        }
    
        .... and so on for all the various parameters you want to add
    
        cmd.CommandText = query;
    
        con.Open();
    
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
             while(reader.Read())
             {
                 // do something with reader -read values 
             }
    
             reader.Close();
        }
    
        con.Close();
    }
    

    【讨论】:

      【解决方案2】:

      使用@firma等参数代替comboBox1.Text

      command.Parameters.Add("@firma", SqlDbType.Varchar);
      command.Parameters["@firma"].Value = comboBox1.Text;
      
       query += " AND firma = @firma ";
      

      将此应用于所有参数

      【讨论】:

      • 好的 - 现在作为下一步,我建议始终定义一个明确的 lengthcommand.Parameters.Add("@firma", SqlDbType.Varchar, 100);
      • 因此查询执行计划会有什么不同??还是性能??
      • 不,它对性能没有任何影响 - 但它可能会避免您在没有明确指定长度的情况下遇到意外的、令人不快的惊喜 - 例如默认长度将使用 1 个字符.....
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 2011-02-12
      • 2012-06-09
      相关资源
      最近更新 更多