我试图了解如何从定义为 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/