System.Data.SqlClient.SqlException: 从字符串转换日期和/或时间时,转换失败

string hotel = Request.Params["hotel_name"];
DateTime start =Convert.ToDateTime( Request.Form["start"]);
DateTime over = Convert.ToDateTime(Request.Form["over"]);
string ourhotelconn = getConnStr();
SqlConnection ourhotelshopconn = new SqlConnection(ourhotelconn);
ourhotelshopconn.Open();
string select3 = "select count(*) from reservedetail where hotel_name=' + hotel + ' and reserve_startTime between ' + start + ' and ' + over + ' and reserve_overTime between ' + start + ' and ' + over + ' ";

SqlCommand timecommand = new SqlCommand(select3, ourhotelshopconn);
object objtime = timecommand.ExecuteScalar();
int c4 = Convert.ToInt32(timecommand.ExecuteScalar());

这里有两个地方发生了字符串转日期:

一是 Convert.ToDateTime 这个地方,如果传入的字符串不是有效的 DateTime 格式,会报错,但这个错应该和 SqlClient 无关,所以,你这个错不是出现在这里。
还有一个地方可能很容易被忽略,那就是数据库查询的时候,你这里的 start 和 over 自己手动转成了 DateTime,但后面又用在拼接 sql 语句中,会自动转成字符串,用的是 DateTime的 ToString() 方法,而这个方法如果没有传参数的话,转出的时间格式和电脑上设置的时间格式是有关的,比如你手机上的时间显示了星期,这个转换后的字符串也会带星期。
但你数据库中应该的类型应该是 DateTime 而不是字符串的,所以,进行数据库操作时会把这个字符串自动转成 DateTime 类型,你报的错应该就是这里了。
解决方法很多,最简单的就是你传入的 start 和 over 本来就是字符串的,如果是合法的字符串,就不需要转成 DateTime 了,因为后面还要拼接 sql 语句,还得转成字符串。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-04-03
下面语句BeginTime 是字符串么,如果是的话先转成datetime类型