MySql“选择位置"和C# [英] MySql "Select Where" and C#
问题描述
如何从"Select Where"语句中读取返回值,每次运行时,标签中都没有出现返回值,也没有语法错误.
How can i read the return value from "Select Where" statement , every time i run no return value appear in the label, and no syntax error.
command.CommandText = "select product_price from product where product_name='"+x+"';";
connection.Open();
Reader = command.ExecuteReader();
while(Reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
connection.Close();
推荐答案
如果product_price
列在MySQL中不是TEXT
类型,则Reader.GetString(0)
将(取决于Oracle如何实现读取器)抛出Exception或返回空字符串.我认为后者正在发生.
If the product_price
column is not of type TEXT
in MySQL, the Reader.GetString(0)
will (depending on how the reader was implemented by Oracle) throw an Exception or return an empty string. I would think the latter is happening.
通过DataReader
检索值要求您知道数据类型.您不能简单地为每种类型的字段读取字符串.例如,如果数据库中的字段是Integer,则需要使用GetInt32(...)
.如果它是DateTime
,请使用GetDateTime(...)
.在DateTime
字段上使用GetString
无效.
Retrieving the value through a DataReader
requires you to know the data type. You can not simply read a string for every type of field. For example, if the field in the database is an Integer, you need to use GetInt32(...)
. If it is a DateTime
use GetDateTime(...)
. Using GetString
on a DateTime
field won't work.
编辑
这就是我编写此查询的方式:
EDIT
This is how I'd write this query:
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();
}
}
}
这篇关于MySql“选择位置"和C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!