在向SQL Server注入数据时,将函数作为参数传递

本文关键字:函数 参数传递 SQL Server 注入 数据 在向 | 更新日期: 2023-09-27 18:13:25

我写了一个GetLoan函数:

private void GetLoan(RadioButton radiobutton)
{
        if(radiobutton.Checked)
        {
            MessageBox.Show(radiobutton.Text);
        }
}
为了从单选按钮中获得必要的数据,我这样做了,
bookCom = new SqlCommand("UPDATE d_Book SET ISBN = @isbn, Author = @author, Title = @title, Publisher = @publisher, Date = @date, Loan = @loan WHERE ISBN = @isbn ", bookCon);
String ISBN = textISBN.Text;
String Author = textAuthor.Text;
String Title = textTitle.Text;
String Publisher = textPublisher.Text;
String Date = textDate.Text;
GetLoan(rdbtn_Yes); // worked fine
GetLoan(rdbtn_No);  // worked fine
bookCom.Connection = bookCon;
bookCon.Open();
if (bookCon.State == ConnectionState.Open)
{
    bookCom.Parameters.AddWithValue("@isbn", ISBN);
    bookCom.Parameters.AddWithValue("@author", Author);
    bookCom.Parameters.AddWithValue("@title", Title);
    bookCom.Parameters.AddWithValue("@publisher", Publisher);
    bookCom.Parameters.AddWithValue("@date", Date);
    bookCom.Parameters.Add("@loan", SqlDbType.Char).Value = GetLoan; // didn't work at all
}

有什么办法可以让GetLoan工作吗?

在向SQL Server注入数据时,将函数作为参数传递

必须在函数中指定返回类型:

    private string GetLoan(RadioButton radiobutton)
    {
        if (radiobutton.Checked)
        {
            return "yes";
        }
        else
        {
            return "no";
        }
    }

或在一行代码中作为bool值:

    private bool GetLoan(RadioButton radiobutton)
    {
        return radiobutton.Checked;
    }

然后始终需要传递RadioButton作为参数。修改

bookCom.Parameters.Add("@loan", SqlDbType.Char).Value = GetLoan;

bookCom.Parameters.Add("@loan", SqlDbType.Char).Value = GetLoan(rdbtn_Yes);

但是为什么不简单点,直接检查哪一个被选中了呢?

String Loan = "no";
if (rdbtn_Yes.Checked == true)
{
    Loan = "yes";
}
bookCom.Parameters.Add("@loan", SqlDbType.Char).Value = Loan;

通过阅读提供的代码片段,我理解您需要询问用户是否对贷款感兴趣。您可以考虑使用复选框,而不是单选按钮来表示是或否,然后使用下面的函数。

private string GetLoan(CheckBox chkBxGetLoan)
{
    //returns string value as output.
    return chkBxGetLoan.Checked ? "Y" : "N";
}

private char GetLoan(CheckBox chkBxGetLoan)
{
    //returns char value as output.
    return chkBxGetLoan.Checked ? 'Y' : 'N';
}