【发布时间】:2017-09-21 11:02:00
【问题描述】:
我无法弄清楚我的代码出了什么问题或者解决方案可能是什么 我也不知道如何编写和获取要放回日期时间选择器的日期时间。
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 * 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.GetString("Barcodes");
string sName = myReader.GetString("Name");
var sDate = myReader.GetDateTime("EDate");
string sQuantity = myReader.GetInt32("Quantity")).ToString();
string sPrice = myReader.GetInt32("Price")).ToString();
tbxBar.Text = sBarcode;
tbxName.Text = sName;
sDate = dateDate.Value;
tbxPrice.Text = sPrice;
tbxQua.Text = sQuantity;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
编辑 2:我收到错误消息
“当没有数据可用时进行了无效的读取尝试”
我的数据库中的所有字符串都有数据,但我仍然收到此错误
【问题讨论】:
-
您能否提供确切的错误信息?我认为
string sQuantity = myReader.GetInt32("Quantity")).ToString();或string sPrice = myReader.GetInt32("Price")).ToString();都是错误的。检查您的数据库中有哪些数据类型。 -
有了这些信息,我们只能猜测。我的猜测是价格或数量或两者都不是 int。
-
无法从字符串转换为 int 是我悬停时得到的结果,但我无法运行代码,因为“条形码”并且所有这些都带有红色下划线
-
您应该始终使用parameterized queries。这种字符串连接对SQL Injection 攻击开放。还可以使用
using语句自动处理您的连接和命令 -
您的问题是关于为什么您收到错误“无法从字符串转换为 int”,答案是因为方法
GetString、GetDateTime和GetInt32适用于字段索引的字段名称。接受答案并尝试自己解决程序的解决方案或提出有关按名称获取字段值的新问题(此处也已回答)
标签: c# sql datetime datetimepicker