C# - 如何将 SQL Server 时间(7)检索到 TimeSpan

标签 c# asp.net sql-server casting timespan

我试图了解如何从定义为 Time(7) 的 SQL Server 2012 表列中检索时间数据。我到处都看过,并为此苦苦挣扎。这是我用来尝试让它工作的一些简单代码。你能帮帮我吗??

当下面的代码运行时(使用 Visual Studio 2013),我在 TimeSpan DBStartTime... 行收到错误:

Unable to cast object of type 'System.TimeSpan' to type 'System.IConvertible'.

我不知道如何解决这个问题。

var cnnString = ConfigurationManager.ConnectionStrings["TaktBoardsConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(cnnString); 

SqlCommand comm = new SqlCommand();
comm.CommandText = "SELECT * FROM ScheduleDetail WHERE ScheduleID = " + lstShifts.SelectedValue;
comm.CommandType = CommandType.Text;
comm.Connection = conn;

SqlDataReader reader;

conn.Open();
reader = comm.ExecuteReader(); 

while (reader.Read())
{
    TimeSpan DBStartTime = Convert.ToDateTime(reader["StartTime"]).TimeOfDay;
    TimeSpan DBEndTime = Convert.ToDateTime(reader["EndTime"]).TimeOfDay;

    // Add more coding once this works.
}

conn.Close();

最佳答案

不要使用 Convert.ToDateTime 读取器已经返回一个 Timespan,直接进行转换即可。

    TimeSpan DBStartTime = (TimeSpan)reader["StartTime"];
    TimeSpan DBEndTime = (TimeSpan)reader["EndTime"];

此外,与您的问题无关,但您没有为 ScheduleID = "+ lstShifts.SelectedValue; 使用参数,您确实应该这样做。您也没有使用 using 语句,当您的代码抛出异常时,您并没有关闭连接对象。

var cnnString = ConfigurationManager.ConnectionStrings["TaktBoardsConnectionString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(cnnString))
using(SqlCommand comm = new SqlCommand())
{
    comm.CommandText = "SELECT * FROM ScheduleDetail WHERE ScheduleID = @ScheduleID";
    comm.Parameters.Add("@ScheduleID", SqlDbType.Int).Value = lstShifts.SelectedValue;
    comm.CommandType = CommandType.Text;
    comm.Connection = conn;

    conn.Open();

    using(SqlDataReader reader = comm.ExecuteReader())
    {
        while (reader.Read())
        {
             TimeSpan DBStartTime = (TimeSpan)reader["StartTime"];
             TimeSpan DBEndTime = (TimeSpan)reader["EndTime"];
            // Add more coding once this works.
        }
    }
}

关于C# - 如何将 SQL Server 时间(7)检索到 TimeSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32720415/

相关文章:

c# - 在C#中将项目添加到字符串数组列表

c# - 在 WPF 中添加 X 关闭按钮

c# - 使用 asp.net 遍历文本框

c# - Entity Framework 连接池 : how to inject UserId into SQL Servers session_context?

sql-server - 我可以在 SQL 查询中使用什么来帮助我确定为什么我的查询没有返回任何数据结果

sql - 比较 T-SQL Between 和 '<' '>' 运算符的性能差异?

c# - VST插件: using FFT on audio input buffer with arbitrary size,怎么办?

c# - 年份无法使用正则表达式正确显示

javascript - 如何从Aspx页面发送Json数据

sql-server - postgresql(PostGRES) 和 SQL (Spatial) 结果的差异