MySql“选择位置”和C#

时间:2012-03-20 12:51:00

标签: c# mysql wpf

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

4 个答案:

答案 0 :(得分:3)

如果product_price列在MySQL中不是TEXT类型,则Reader.GetString(0)将(取决于Oracle如何实现读取器)抛出异常或返回空字符串。我认为后者正在发生。

通过DataReader检索值需要您知道数据类型。您不能简单地为每种类型的字段读取字符串。例如,如果数据库中的字段是Integer,则需要使用GetInt32(...)。如果是DateTime使用GetDateTime(...)。在GetString字段上使用DateTime将无效。

修改
这是我写这个查询的方式:

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();
        }
    }
}

答案 1 :(得分:2)

要附加我的评论,您的方法有三个问题,这些问题不属于您的问题:

因此,代码的更正确版本如下所示:

// 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().

答案 2 :(得分:0)

你必须创建一个读者的变量

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();
}

答案 3 :(得分:0)

您应该在@pname上写上不带''的字符,否则它将无法正常工作。

而不是:

  

从产品中选择product_price,其中product_name ='@ pname'

您应该这样写:

  

从产品中选择product_price,其中product_name = @ pname