如何使用SqlDataReader获取浮点值? [英] How to get float value with SqlDataReader?
问题描述
在我的数据库中,我具有NextStatDistanceTime值作为浮点数。当执行 浮动时间= reader.GetFloat(0);
行时,给出的错误为
In my database, I have NextStatDistanceTime value as a float. When "float time = reader.GetFloat(0);
" line excecuted, it gives an error of
系统无效的强制转换异常
system invalid cast exception
如何在此代码中从sql命令获取浮点值?
How can I get float value from sql command in this code?
这是我的代码:
using (SqlConnection conn = new SqlConnection(@"<myconnectionstring>"))
{
float totaltime = 0;
for (int i = startStationIndex; i < endStationIndex; i++)
{
SqlCommand command = new SqlCommand("SELECT NextStatDistanceTime FROM [MetroDatabase].[dbo].[MetroStation] WHERE StationIndex = " + i + "", conn);
try
{
conn.Open();
command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
float time = reader.GetFloat(0);
totaltime = totaltime + time;
conn.Close();
}
}
}
catch (Exception ex)
{
result = ex.Message;
Console.WriteLine(ex.Message);
}
}
}
推荐答案
我想是时候放一张桌子了。
It's time for a little table, I think.
T-SQL type name | .NET equivalent | C# type name | DataReader method
----------------+-----------------+--------------+------------------------
FLOAT | System.Double | double | IDataReader.GetDouble()
REAL | System.Single | float | IDataReader.GetFloat()
请注意, GetFloat
名称错误-应该是 GetSingle
,因为 float
是C#特定的名称。例如,在VB.NET中这没有任何意义。
Note that GetFloat
has the wrong name -- it should be GetSingle
, because float
is a C#-specific name. It makes no sense in VB.NET, for example.
因此,如果您的数据库列的类型为 FLOAT
,请使用 GetDouble
而不是 GetFloat
进行读取。数据读取器方法不执行转换;有一个通用的 GetValue
方法可将值作为对象
获取,然后可以进一步转换。
So, if your database column is of type FLOAT
, read it using GetDouble
, not GetFloat
. The data reader methods do not perform conversions; there is a generic GetValue
method to get the value as an object
that you can then convert further.
顺便说一句,这并不是唯一的妙处-.NET浮点类型支持非规范化的值,而T-SQL类型则没有,因此,.NET代码中可能会有无法成功存储在数据库中的浮点数,即使这些类型匹配。
Incidentally, this is not the only subtlety -- the .NET floating-point types support denormalized values, whereas the T-SQL types do not, so it is possible to have floating-point numbers in your .NET code that can't be successfully stored in the database, even if the types match.
这篇关于如何使用SqlDataReader获取浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!