【发布时间】:2016-09-17 13:41:00
【问题描述】:
在我的数据库中,我将 NextStatDistanceTime 值作为浮点数。执行“float time = reader.GetFloat(0);”行时,报错
系统无效转换异常
如何从这段代码中的 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);
}
}
}
【问题讨论】:
-
数据库中的类型是什么?
-
@JonSkeet 他提到了它,它在数据库中的“浮动”。
-
@RanjitSingh:哎呀,错过了。在那种情况下,我真的希望它会很好......我的猜测是它不是真的数据库中的浮点数。知道调用
reader.GetValue(0)的结果会很有趣——那是什么类型? -
顺便说一句,您应该立即开始使用参数化 SQL。
-
哦,为什么不让数据库为你求和呢?获取所有值似乎很奇怪,只是将它们相加......