如何使用SqlDataReader获取浮点值?
在我的数据库中,我将NextStatDistanceTime值作为float。 当“ float time = reader.GetFloat(0);
”行已超出时,它会给出错误
系统无效的转换exception
如何在此代码中从sql命令获取浮点值?
这是我的代码:
using (SqlConnection conn = new SqlConnection(@"")) { 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); } } }
我觉得是时候换一张小桌了。
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
读取它。 数据读取器方法不执行转换; 有一个通用的GetValue
方法可以将值作为object
,然后可以进一步转换。
顺便说一句,这不是唯一的细微之处 – .NET浮点类型支持非规范化值 ,而T-SQL类型则不支持,因此.NET代码中的浮点数可能不是成功存储在数据库中,即使类型匹配。
正如你在这里看到的那样,sql-server float映射到.NET double,所以你需要使用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 }
我的猜测是数据库返回double值,尝试将其设置为Double
并将其转换为float
(如果需要)。
float time= (float) reader.GetDouble(0);
你可以试试:
float time = float.Parse(reader[0].ToString());
另请注意(尽管与您的Q无关)您不需要运行
command.ExecuteNonQuery();
试试这个
convert.ToSingle(reader["NextStatDistanceTime"])
或者做
double value = (double)reader["NextStatDistanceTime"]
浮点数的sql相当于c#的两倍,你可以在这里看到类似的映射
while (reader.Read()) { object initialTime = reader["NextStatDistanceTime"]; float time; float.TryParse(initialTime.ToString(), out time); totaltime = totaltime + time; conn.Close(); }
试试这个,这将从数据库中获取时间然后将其转换为浮点数,如果你愿意,你可以把reader["NextStatDistanceTime]
放在tryparse中,但为了让它更清楚,我已经这样做了。
任何问题让我知道
可能是数据库类型和c#类型之间的精度不匹配。 尝试像(float)reader.GetDouble(0);
上述就是C#学习教程:如何使用SqlDataReader获取浮点值?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ctvol.com/cdevelopment/986817.html