簡體   English   中英

SQL 數據庫 If-Else 語句

[英]SQL Database If-Else statement

private void btnChange_Click(object sender, EventArgs e)
{
    con.Open();

    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "update Customer set MembershipPoint='" + textMembershipPoint.Text + "' where NameCustomer='" + textNameCustomer.Text + "'";

    cmd.ExecuteNonQuery();

    if (cmd.ExecuteScalar() != null)
    {
        textMembershipPoint.Text = Convert.ToString(cmd.ExecuteScalar());
    }
    else if (cmd.ExecuteScalar() != )
    {
        MessageBox.Show("Invalid Name of Customer.");
    }
    else if (cmd.ExecuteScalar() != )
    {
        MessageBox.Show("Invalid Membership Point. Only Number Allowed.");
    }
    else
    {
        MessageBox.Show("Membership Point is changed.");
    }

    con.Close();

    display_data();
}

我有一個名為Customer的數據庫表, NameCustomer包含ID_CustomerNameCustomerMembershipPoint列。

當客戶輸入不在Customer表中的名稱時,輸出將顯示“Invalid Name of Customer.”。

如果客戶輸入無效的 MembershipPoint,輸出將顯示“Invalid Membership Point. Only Number Allowed.”。

如果一切正常,則輸出將顯示“Membership Point is changed.”。

誰能告訴我我需要為 if else 語句做些什么才能實現這一目標?

首先,您必須學習使用參數化查詢以避免#1 漏洞——SQL 注入! 這樣做 -總是- 沒有例外。

其次 - 現在,您正在多次執行UPDATE語句,這非常糟糕......只需執行一次,記錄結果,然后僅根據結果進行推理 - 不要多次執行 SQL 命令。

所以嘗試這樣的事情:

private void btnChange_Click(object sender, EventArgs e)
{
    // check if the membership points text is a valid INT or not
    int membershipPoints = 0;
    
    if (!int.TryParse(textMembershipPoint.Text, out membershipPoints))
    {
        MessageBox.Show("Invalid Membership Point. Only Number Allowed.");
        return;
    }


    // use a properly parametrized query
    string updateQuery = "UPDATE dbo.Customer SET MembershipPoint = @Points WHERE NameCustomer = @CustomerName;";
    
    // put your SqlCommand into a proper "using" block
    using (SqlCommand cmd = new SqlCommand (updateQuery, con))
    {
        // define the parameters and set their values
        cmd.Parameters.Add("@Points", SqlDbType.Int).Value = membershipPoints;
        cmd.Parameters.Add("@CustomerName", SqlDbType.VarChar, 100).Value = textNameCustomer.Text;
        
        // open connection, execute UPDATE, record number of rows updated, close connection
        con.Open();
        int rowsUpdated = cmd.ExecuteNonQuery();
        con.Close();
        
        // now reason just on the result
        if (rowsUpdated > 0)
        {
            // some rows were updated --> success
            MessageBox.Show("Success - rows updated");
        }
        else
        {
            // no rows were updated --> 
            MessageBox.Show("No rows updated - most likely invalid customer name");
        }
    }
    
    
    display_data();
}

暫無
暫無

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

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