簡體   English   中英

對sqlcommand.executescalar使用說明

[英]using stating for sqlcommand.executescalar

我正在使用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上向我建議的用於檢查預先存在的記錄的代碼...雖然效果很好,但是我想知道是否有一種方法可以將參數用於客戶編號,因為此變量是通過表單輸入的,我想保護它免受注射。 當這樣的using語句中的cmdCheck參數在哪里創建?

初始化命令后,添加參數。 一個便捷的方法是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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM