【问题标题】:C#, problems with getting double values from MySQL databaseC#,从 MySQL 数据库获取双精度值的问题
【发布时间】:2012-12-17 18:17:54
【问题描述】:

我有一个带有“Products”表的 MySQL 数据库。 “Products”中的一列称为“Price”,数据类型为“double”。

我需要从该列中检索值,因此我创建了一个阅读器等:

MySQLCommand cmd = new MySQLCommand("SELECT Price FROM Products", connection);
MySQLDataReader reader = cmd.ExecuteReaderEx();

if (reader.HasRows == true)
{
  while (reader.Read() == true)
  {
    price = reader["Price"]).ToString();
  }
}

问题是价格未设置为预期值。如果数据库中的值为“299.95”,则价格设置为“29995.0”。

知道为什么会这样吗?可以做些什么来解决它?

【问题讨论】:

  • off topic 一般价格表示decimal,但您似乎将其维护为string
  • 查看数据库时,值真的是299.95吗?

标签: c# mysql double datareader


【解决方案1】:

这是因为 toString() 使用了当前的 CultureInfo! 是否用逗号或点分隔双精度取决于文化。

CultureInfo

另见this Stackoverflow 问题!

如果您调试它,您应该会看到,该 reader["Price"] 正在返回一个 Object (type=Object{double})。这里的值正确吗?我猜是这样,所以只需执行以下操作即可显示双值:

string display = double.Parse(reader["Price"], CultureInfo.InvariantCulture).ToSring(CultureInfo.CurrentCulture);
System.Diagnostics.Debug.WriteLine(display);

【讨论】:

  • 听起来很合理,但 reader["Price"] 返回“29995.0”。所以看起来现在试图让它理解“。”已经太晚了。应解释为“,”。
  • 如果你尝试用双精度解析它会发生什么? double test = (double) reader["Price"] 这有效吗?如果没有,我不知道你的问题是什么......
  • 不行不行,当时read["Price"]已经是"29995.0"了。
  • 在代码中的某处添加这一行可以解决问题(我将它添加到表单加载事件中):System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
【解决方案2】:

试试

MySQLCommand cmd = new MySQLCommand("SELECT Price FROM Products", connection);
MySQLDataReader reader = cmd.ExecuteReaderEx();

if (reader.HasRows)
{
  while (reader.Read())
  {
    price = double.Parse(reader["Price"]).ToString());
  }
}

价格变量应该是双精度数据类型

【讨论】:

  • 试过了,还是不行。不过感谢您试一试。
  • 你的 CultureInfo 是什么?如果您的数据库记录是使用美国格式保存的,但您的机器具有西班牙语或其他文化,那么您将不会根据您的数据库格式获得相同的记录。
猜你喜欢
  • 1970-01-01
  • 2013-12-28
  • 2017-03-15
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
相关资源
最近更新 更多