private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Barcodes, Name, EDate, Quantity, Price FROM Products where Name='" + cbxProducts.Text + "' ; ";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
string sBarcode = myReader["Barcodes"].ToString();
string sName = myReader["Name"].ToString();
var sDate = myReader["EDate"];
string sQuantity = myReader["Quantity"].ToString();
string sPrice = myReader["Price"].ToString();
tbxBar.Text = sBarcode;
tbxName.Text = sName;
sDate = dateDate.Value;
tbxPrice.Text = sPrice;
tbxQua.Text = sQuantity;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
当我尝试使用此代码时,我只是收到错误消息 “当没有数据可用时,无效尝试读取”我的数据库中有数据,但它仍然无效。
答案 0 :(得分:2)
Reader
对象逐个获取行,我们需要告诉它使用Read()
方法来获取下一行。
你需要调用Read()
对象的SqlDataReader
方法来读取每一行,如果预期有单行,那么你可以通过if
otehrwise做一个你需要做的事情。 while
循环如:
while(myReader.Read())
{
string sBarcode = myReader["Barcodes"].ToString();
string sName = myReader["Name"].ToString();
var sDate = myReader["EDate"];
string sQuantity = myReader["Quantity"].ToString();
string sPrice = myReader["Price"].ToString();
tbxBar.Text = sBarcode;
tbxName.Text = sName;
sDate = dateDate.Value;
tbxPrice.Text = sPrice;
tbxQua.Text = sQuantity;
}
另一件事是在创建查询时不应该进行字符串连接,请考虑使用参数化查询,因为您的代码对SQL Injection开放。您可以阅读How to: Execute a Parameterized Query知道如何编写参数化查询。