如何使用 SqlDataReader 获取浮点值?

How to get float value with SqlDataReader?

在我的数据库中,我的 NextStatDistanceTime 值为浮点数。当执行“float time = reader.GetFloat(0);”行时,它给出了

的错误

system invalid cast exception

如何从这段代码中的 sql 命令获取浮点值?

这是我的代码:

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

}

你可以试试:

float time = float.Parse(reader[0].ToString());

另请注意(尽管与您的问题无关)您不需要 运行

command.ExecuteNonQuery();
 while (reader.Read())
 {
     object initialTime = reader["NextStatDistanceTime"];
     float time;
     float.TryParse(initialTime.ToString(), out time);

     totaltime = totaltime + time;
     conn.Close();
 }

试试这个,这将从数据库中获取时间,然后将其转换为浮点数,如果需要,您可以将 reader["NextStatDistanceTime] 放在 tryparse 中,但为了更清楚,我是这样做的.

有任何问题请告诉我

试试这个

convert.ToSingle(reader["NextStatDistanceTime"])

或者

double value = (double)reader["NextStatDistanceTime"]

sql的float相当于c#的double,可以看到类似的映射here

可能是数据库类型和 C# 类型之间的精度不匹配。 尝试像 (float)reader.GetDouble(0);

这样的转换

我的猜测是数据库正在返回双精度值,尝试将其获取为 Double 并将其转换为 float(如果需要)。

float time= (float) reader.GetDouble(0);

如你所见here a sql-server float maps to a .NET double, so you need to use GetDouble:

double totaltime = 0;  // necessary, double is wider than float
// ...

while (reader.Read())
{
    double time = reader.GetDouble(0);
    totaltime = totaltime + time;
    // conn.Close(); no, not in this loop, should be closed in the finally or via using-statement
}

我想是时候 table 了。

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 中没有意义。

因此,如果您的数据库列是 FLOAT 类型,请使用 GetDouble 而不是 GetFloat 读取它。数据 reader 方法 执行转换;有一种通用的 GetValue 方法可以将值作为 object 获取,然后您可以进一步转换。

顺便说一句,这不是唯一的微妙之处 -- .NET 浮点类型支持 denormalized values,而 T-SQL 类型不支持,因此可以有浮点- .NET 代码中无法成功存储在数据库中的点数,即使类型匹配也是如此。