C# 如何使SqlDataReader获取时间(7)类型变量?
我有一个SQL Server表,如下所示:C# 如何使SqlDataReader获取时间(7)类型变量?,c#,sql-server,C#,Sql Server,我有一个SQL Server表,如下所示: userID int xCoordinate int yCoordinate int recordTime time(7) itemId int 我想获得给定用户的所有录制时间(现在假设用户1)。 我为此使用了以下代码: public static void something() { string stmt = "select * from GazeTable where id = " + 1 + " ;"; SqlConnect
userID int
xCoordinate int
yCoordinate int
recordTime time(7)
itemId int
我想获得给定用户的所有录制时间(现在假设用户1)。
我为此使用了以下代码:
public static void something()
{
string stmt = "select * from GazeTable where id = " + 1 + " ;";
SqlConnection conn = GetConnection();
SqlCommand cmd = new SqlCommand(stmt, conn);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetDateTime(3));
}
}
conn.Close();
}
但它抛出了一个错误
System.Data.dll中发生类型为“System.InvalidCastException”的未处理异常
也就是说,此作业无效
如何以(“HH:mm:ss.ffff”)的形式为我表中的每个recordTime
打印时间?SQL类型time(7)
相当于C类型TimeSpan
而不是DateTime
,要获得DateTime
值,SQL类型必须是DateTime
因此,只需将代码更改为读取TimeSpan而不是DateTime:
public static void something()
{
string stmt = "select * from GazeTable where id = " + 1 + " ;";
SqlConnection conn = GetConnection();
SqlCommand cmd = new SqlCommand(stmt, conn);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetTimeSpan(3));
}
}
conn.Close();
}
SQL类型Time(7)
相当于C类型TimeSpan
而不是DateTime
,要获得DateTime
值,SQL类型必须是DateTime
因此,只需将代码更改为读取TimeSpan而不是DateTime:
public static void something()
{
string stmt = "select * from GazeTable where id = " + 1 + " ;";
SqlConnection conn = GetConnection();
SqlCommand cmd = new SqlCommand(stmt, conn);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetTimeSpan(3));
}
}
conn.Close();
}
在我的脑海中,您可能需要使用这样的东西(尚未测试):
您应该将time(7)列转换为timespan,但不能直接将其转换为datetime。在我看来,您可能需要使用类似的内容(尚未测试):
您应该将时间(7)列转换为时间跨度,您不能直接将其转换为日期时间。使用
reader.GetInt(2)
?如果我没有弄错的话,SQL类型time(7)
不会转换为datetime
,但在C#中转换为timespan
,所以请尝试reader.GetTimeSpan(3)
instead@ntohl是的does@BojanB哦,我的天哪,它起作用了,我到处搜索,一直说,datetime相当于sql的时间,非常感谢much@Danabey没有问题:)与reader.GetInt(2)
获得y坐标是否有效?如果我没有弄错SQL类型时间(7)
不会在C#中转换为DateTime
而是TimeSpan
,因此请尝试reader.GetTimeSpan(3)
instead@ntohl是的does@BojanB哦,我的天哪,它起作用了,我到处搜索,一直说,datetime相当于sql的时间,非常感谢much@Danabey没问题:)也许这也行,但我将确保没有Console.WriteLine(“找不到行”)代码>案例。所以无论如何,谢谢。这可能也会起作用,但我会确保没有控制台。WriteLine(“未找到行”)代码>案例。因此,无论如何,可能需要一个cast(SqlDataReader)读取器
该GetTimeSpan
在系统中不可用。Data.IDataReader
可能需要一个cast(SqlDataReader)读取器
该GetTimeSpan
在系统中不可用。Data.IDataReader