And*_*ndy 2 c# sql-server asp.net timespan casting
我试图了解如何从定义为的SQL Server 2012表列中检索时间数据Time(7).我到处寻找,并为此而苦苦挣扎.这里有一些简单的代码,我只是试图让它工作.你能帮我么??
当下面的代码运行时(使用Visual Studio 2013),我得到了错误TimeSpan DBStartTime...:
无法将类型为"System.TimeSpan"的对象强制转换为"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();
Run Code Online (Sandbox Code Playgroud)
不要使用Convert.ToDateTime读者已经返回Timespan,只需做直接演员.
TimeSpan DBStartTime = (TimeSpan)reader["StartTime"];
TimeSpan DBEndTime = (TimeSpan)reader["EndTime"];
Run Code Online (Sandbox Code Playgroud)
此外,与您的问题无关,但您没有使用参数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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7319 次 |
| 最近记录: |