当尝试从数据库中检索数据时,我收到错误“InvalidOperationException未处理”

时间:2018-01-28 18:21:19

标签: c# sql-server

我有一个名为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 个答案:

答案 0 :(得分:1)

这可能不是您正在寻找的确切答案,但您需要注意以下事项:

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注入攻击。尝试使用变量来阻止它。