使用SQL数据读取器C#的参数化查询

时间:2015-06-16 14:34:47

标签: c# sql-server

我知道由于SQL注入,非参数化查询不受欢迎。好吧,我的应用程序中有很多查询容易受到SQL注入的影响。我似乎无法用SqlDataReader来解决这个问题。我可以使用ExecuteNonQuery而不是SQLDataReader

有人可以给我一些指针和/或最好的方法示例,查询正在执行并准确返回它应该是什么,我只是想让它尽可能安全....

代码:

string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
                 + "WHERE [customerName] = '" + customer + "' AND " + "[customerPin] = '" + customerID + "'";

 sqlCmd = new SqlCommand(myQuery, conn);
 sqlCmd.Connection.Open();
 SqlDataReader rdr2 = sqlCmd.ExecuteReader();

  if (rdr2.HasRows)
     {
        rdr2.Read();

        shoeSize= rdr2["Shoe Size"].ToString();       
        shoeBrand= rdr2["Shoe Brand"].ToString();
     }
     conn.close();

2 个答案:

答案 0 :(得分:5)

你去了

string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
                 + "WHERE [customerName] = @customerName AND [customerPin] = @customerID"

 sqlCmd = new SqlCommand(myQuery, conn);
 sqlCmd.Connection.Open();
 sqlCmd.Parameters.AddWithValue("@customerName", customerName);
 sqlCmd.Parameters.AddWithValue("@customerID", customerID");
 --rest stays the same as before

而@customerName和@customerID现在是你的参数。因此,即使顾客的名字应该是像#34; Bigler,Fabian' DROP TABLE [myTable]"不起作用。它完全消除了“邪恶”的可能性。输入更改查询的含义。

非参数化查询不仅仅是“不受欢迎”。对您,您的公司,当然还有您的客户来说,这可能是灾难性的。

答案 1 :(得分:2)

像这样:

        string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
              + "WHERE [customerName] = @customerName AND [customerPin] = @customerPin";

        sqlCmd = new SqlCommand(myQuery, conn);
        sqlCmd.Connection.Open();
        sqlCmd.Parameters.Add("@customerName", SqlDbType.NVarChar, 50).Value = customer;
        sqlCmd.Parameters.Add("@customerPin", SqlDbType.NVarChar, 20).Value = customerID;
        SqlDataReader rdr2 = sqlCmd.ExecuteReader();

        if (rdr2.HasRows)
        {
            rdr2.Read();

            shoeSize = rdr2["Shoe Size"].ToString();
            shoeBrand = rdr2["Shoe Brand"].ToString();
        }
        conn.close();