C#, problems with getting double values from MySQL database

和自甴很熟 提交于 2019-12-14 02:22:38

问题


I have a MySQL database with the table "Products". A column in "Products" is called "Price" and has the datatype "double".

I need to retrieve the values from that column, so I create a reader, etc.:

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

Problem is that price isn't set to the expected value. If the value in the database is "299.95", price is set to "29995.0".

Any idea why this is happening? And what can be done to fix it?


回答1:


This is, because toString() uses the current CultureInfo! It depends on the culture if a double is separated by a comma or a dot.

CultureInfo

See also this Stackoverflow Question!

If you debug it you should see, that reader["Price"] is returning an Object (type=Object{double}). Is here the value correct? I guess it is, so just make following to display the double-value:

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



回答2:


Try

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

price variable should be in double data type



来源:https://stackoverflow.com/questions/14138013/c-problems-with-getting-double-values-from-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!