使用stating for sqlcommand.executescalar

时间:2013-01-04 09:00:11

标签: c# asp.net parameters using

我使用using声明来验证客户编号。

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
    connection.Open();

    using (SqlCommand cmdCheck = new SqlCommand("SELECT COUNT(CUSTOMER_NO) FROM WEBSITE_CUSTOMERS WHERE UPPER(CUSTOMER_NO) = '" + strCustomer.Trim().ToUpper() + "';", connection))
    {
        int nExists = (int)cmdCheck.ExecuteScalar();
        if (nExists > 0) 
            return true;
        else
            return false;
    }
}

这是先前通过stackoverflow向我建议的用于检查预先存在的记录的代码......它运行良好,但我想知道是否有一种方法可以使用它的参数作为客户编号,因为输入了此变量通过表格,我想保护它免受注射。我在cmdCheck这样的using语句中为{{1}}创建参数?

1 个答案:

答案 0 :(得分:5)

初始化命令后添加参数。一种方便的方法是AddWithValue

const string sql = @"SELECT 
                        COUNT(CUSTOMER_NO) 
                     FROM 
                        WEBSITE_CUSTOMERS 
                     WHERE 
                        UPPER(CUSTOMER_NO) = @CUSTOMER_NO;";

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
    using (SqlCommand cmdCheck = new SqlCommand(sql, connection))
    {
        cmdCheck.Parameters.AddWithValue("@CUSTOMER_NO", strCustomer.Trim().ToUpper());
        connection.Open();
        int nExists = (int)cmdCheck.ExecuteScalar();
        return nExists > 0;
    }
}