1

我正在使用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

4

1 回答 1

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;
    }
}
于 2013-01-04T09:08:24.357 回答