MySql "Select Where" and C#

本文关键字:quot and Select MySql Where | 更新日期: 2023-09-27 18:28:26

如何从"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();

MySql "Select Where" and C#

如果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对象
  • 坏习惯,"" + 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();
}

您应该在没有"的情况下编写@pname,否则它将不起作用。

而不是:

从product_name="@pname"的产品中选择product_price

你应该这样写:

从product_name=@pname 的产品中选择product_price