![](/img/trans.png)
[英]InvalidOperationException when i try to retrieve a password from database, “Invalid attempt to read when no data is present.”
[英]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.