变量如果product_price
列在MySQL TEXT
型的没有,Reader.GetString(0)
会(取决于如何,读者被甲骨文实现)扔一个异常或返回一个空字符串。我会认为后者正在发生。
通过DataReader
检索值需要您了解数据类型。您不能简单地为每种类型的字段读取一个字符串。例如,如果数据库中的字段是整数,则需要使用GetInt32(...)
。如果是DateTime
则使用GetDateTime(...)
。在DateTime
字段上使用GetString
将不起作用。
编辑
我这是怎么会写这个查询:
using (MySqlConnection connection = new MySqlConnection(...))
{
connection.Open();
using (MySqlCommand cmd = new MySqlCommand("select product_price from product where product_name='@pname';", connection))
{
cmd.Parameters.AddWithValue("@pname", x);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
sb.Append(reader.GetInt32(0).ToString());
Price_label.Content = sb.ToString();
}
}
}
是否真的有任何数据库中的相关记录?也许你也可以考虑将名称作为参数 – V4Vendetta 2012-03-20 12:53:42
传递给我,但仍然没有返回出现在标签中,所以我认为读者部分有问题。 – 2012-03-20 12:56:40
你来自VB6的背景,是吗?首先,C#是一种静态语言,所以摆脱这种''“+”习惯来进行类型转换。其次,你想看看[参数化查询](http://bobby-tables.com/)。另外,你应该通过'using()'使用'IDispoable'接口。 – Bobby 2012-03-20 12:58:54