MySql“选择位置”和C#
如何从“Select Where”语句中读取返回值,每次运行时都没有返回值出现在标签中,并且没有语法错误。
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或返回空字符串。 我认为后者正在发生。
通过DataReader
检索值需要您知道数据类型。 您不能简单地为每种类型的字段读取字符串。 例如,如果数据库中的字段是Integer,则需要使用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(); } } }
要附加到我的评论中,您的方法有三个问题,这些问题不属于您的问题:
- SQL注入, 始终使用参数化查询 。
- 资源泄漏, IDisposable-Objects需要妥善处理 。
- 糟糕的习惯,
"" + string
铸造的"" + string
是……呃……不好,没必要。
因此,代码的更正确版本将如下所示:
// using utilizes the IDisposable-Interface, whcih exists to limit the lifetime // of certain objects, especially those which use native resources which // otherwise might be floating around. using(YourConnectionType connection = new YourConnectionType("connectionstring")) { connection.Open(); // You might want to have this in a try{}catch()-block. using(YourCommandType command = connection.CreateCommand()) { command.CommandText = "select product_price from product where product_name=@NAME;"; command.Parameters.Add("NAME", YourTypes.VarChar); command.Parameters[0].Value = x; // For your own sanity sake, rename that variable! using(YourReaderType reader = command.ExecuteReader()) { while(reader.Read()) // If you're expecting only one line, change this to if(reader.Read()). { Price_label.Content = reader.GetString(0); } } } } // No need to close the conenction explicit, at this point connection.Dispose() // will be called, which is the same as connection.Close().
你必须创建一个读者的变量
command.CommandText = "select product_price from product where product_name='"+x+"';"; try { connection.Open(); SqlReader reader = command.ExecuteReader(); while(reader.Read()){ Price_label.Content = "" + Reader.GetString(0); } } catch (Exception) {} finally { connection.Close(); }