将字符转换为日期和/或时间时出现转换失败。

3
如果您能帮我解决问题,那就太好了。我的错误信息如下:
“将日期和/或时间从字符字符串转换失败。”
我的数据库列的类型是datetime。

此时 ctime 变量中的值是什么?这应该能够提示为什么会抛出错误。 - Dan J
2个回答

9
使用参数化查询,您就无需担心日期格式或SQL注入攻击,并使用 using 来确保您的连接被正确释放。
using (var connection = new SqlConnection(yourConnectionString))
using (var command = connection.CreateCommand())
{
   command.CommandText = "insert into YourTable(Col1, Col2) values(@val1, @val2)";
   command.Parameters.AddWithValue("@val1", 123);
   command.Parameters.AddWithValue("@val2", DateTime.Now);

   connection.Open();

   command.ExecuteNonQuery();
}

2
您也可以使用SQL中的GETDATE()函数,它是SQL的预定义函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接