繁体   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