I have a SQL Server table like this:
userID int
xCoordinate int
yCoordinate int
recordTime time(7)
itemId int
I want to get all recording times of a given user (let's say user 1 for now). I used the following code for this:
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();
}
But it throws an error
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll
saying, this assignment is not valid.
How can I print the time in terms of ("HH:mm:ss.ffff"), for each recordTime
in my table?
3条答案
按热度按时间djmepvbi1#
The SQL Type
Time(7)
is equivalent to the C# TypeTimeSpan
notDateTime
, to get aDateTime
Value the SQL Type has to bedatetime
.So just change your code to read TimeSpan instead of DateTime:
zy1mlcev2#
Out of the top of my head, you might need to use something like this (haven't tested):
You should convert the time(7) column to a timespan, you can't convert it directly to a datetime.
mitkmikd3#
Note that if you are using the .NET Framework 4.8 or earlier GetTimeSpan() is not available. Instead you must use (TimeSpan)reader.GetValue(columnIndex)