簡體   English   中英

當嘗試從數據庫中檢索數據時,我收到錯誤“InvalidOperationException未處理”

[英]When trying to retrieve data from the database I get an error “InvalidOperationException was unhandled”

我有一個名為Form1的表單:

有一個ComboBox和一個TextBox ,當我從ComboBox選擇US $時,它必須從數據庫中檢索數據並在TextBox顯示150。

這是myform代碼:

對於ComboBox ;

namespace PCJ_System
{
  public partial class Form1 : Form
  {
    SqlConnection conn;
    SqlCommand cmd;
    SqlDataReader dr;
    public Form1()
    {
        InitializeComponent();
    }

     private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;";
        SqlConnection conn = new SqlConnection(str);
        conn.Open();
        conn = new SqlConnection(str);
        string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
        cmd = new SqlCommand(GetData, conn);
        var returnValue = cmd.ExecuteScalar();

        textBox1.Text = returnValue.ToString();
        conn.Close();
    }

  }
}  

我的數據庫表Forcur:

ID |FC_TYPE |FC_RATE|
1   US$      150
2   UK#      210

我的代碼出了什么問題?

這可能不是您正在尋找的確切答案,但您需要注意以下事項:

1)將DB連接字符串分配給SqlConnection對象並打開連接。

2)由於您要為文本框分配一個值,因此需要使用ExecuteScalar而不是ExecuteReader

解決這個問題后,您應該得到所需的結果。

例:

conn=new SqlConnection(connectionStringHere);
conn.Open();
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();

textBox1.Text = returnValue.ToString();
conn.close();

注意:您仍然在SQL查詢中打開SQL注入攻擊。 嘗試使用變量來阻止它。

暫無
暫無

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

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