C# “datetime”附近的语法不正确。:'System.Data.SqlClient.SqlException”发生在System.Data.dll中,但未在用户代码中处理
我得到这个错误: “datetime”附近的语法不正确 运行我的代码时:C# “datetime”附近的语法不正确。:'System.Data.SqlClient.SqlException”发生在System.Data.dll中,但未在用户代码中处理,c#,sql-server-2012,C#,Sql Server 2012,我得到这个错误: “datetime”附近的语法不正确 运行我的代码时: private static string connectionString = "Data Source=1.1.1.1;Initial Catalog=rs;User Id=rs;Password=rs"; public static List<Cal> getEvents(DateTime start, DateTime end) { List<CalendarEvent> even
private static string connectionString = "Data Source=1.1.1.1;Initial Catalog=rs;User Id=rs;Password=rs";
public static List<Cal> getEvents(DateTime start, DateTime end)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT [ID], [Name], [Room], [Time-in], [Time-out] FROM [rs].[dbo].[res_time] WHERE [Time-in]>=[@Time-in] AND [Time-out]<=[@Time-out]", con);
cmd.Parameters.AddWithValue("[@Time-in]", start);
cmd.Parameters.AddWithValue("[@Time-out]", end);
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CalendarEvent ce = new CalendarEvent();
ce.id = (int)reader["id"];
ce.title = (string)reader["Name"];
ce.description = (string)reader["Room"];
ce.start = (DateTime)reader["Time-in"];
ce.end = (DateTime)reader["Time-out"];
events.Add(cevent);
}
}
return events;
}
首先,您是要返回列表还是列表 要回答您的问题,您需要在VisualStudio中手动解析它
ce.start = Convert.ToDateTime(reader["Time-in"]).ToString();
这是假设您的列数据的格式正确,可以进行转换
更新:
好吧,我搞砸了我的玩具串
试试这个:
// I moved the .ToString() inside the Convert function
ce.start = Convert.ToDateTime(reader["Time-in"].ToString());
得到隐式转换错误是因为它在解析后应用了.ToString,这意味着您试图将字符串值放入DateTime变量中。我的错 对于日期和时间,AddWithValue方法可能有问题。使用
cmd.Parameters.Add("[@Time-in]", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("[@Time-out]", SqlDbType.DateTime).Value = end;
有关AddWithValue方法限制的更多信息,请阅读本文。它的要点是,由于它必须推断正确的数据类型,所以有时它得到的结果是错误的。日期和时间尤其如此
使用Add方法的此重载指定在表上创建列时声明的确切数据类型,有助于确保解析正确的类型。Time in和Time out列的声明数据类型是什么?是DateTime哪一行出错,是SQLException,或者是隐式转换的编译器错误??我在System.Data.dll中遇到了类似“System.Data.SqlClient.SqlException”类型的编译器错误,但未在用户代码中处理其他信息:“datetime”附近的语法不正确。好的,这不是编译器错误,这是运行时异常。现在,消息说异常发生在哪一行?我收到一个错误,无法将类型字符串隐式转换为System.DateTime在SQL中存储数据的格式是什么?能否显示一个时间示例?可能是转换格式问题DataType是DateTimeSample是什么意思?