将c#类型的DateTime插入到SQL的DateTime列中

本文关键字:DateTime SQL 列中 插入 类型 | 更新日期: 2023-09-27 18:10:06

我正试图使INSERT命令到我的SQLEXPRESS数据库并在尝试输入我的DateTime列的值时收到错误。

这是我使用的SQL命令:

SqlDateTime sTime = new SqlDateTime(book.PublishedDate);                
string sql = string.Format("Insert into Books" +
"(Name, PublishDate, IsInternal) Values" +
"('{0}', '{1}', '{2}')",
book.Name, sTime.Value, book.IsInternal);

的书。PublishedDate -是日期时间类型而PublishedDate列是sql DateTime

i收到以下错误:将varchar数据类型转换为日期时间数据类型导致值超出范围。

如何解决

将c#类型的DateTime插入到SQL的DateTime列中

使用参数化查询。实际上,您可能使用的任何数据访问技术都支持它们。它们允许你把日期当作日期来处理,而不是把所有的东西都转换成字符串。

。(ADO。净SqlCommand)

SqlCommand cmd = new SqlCommand("Insert into Books (Name,PublishDate,IsInternal) Values (@Name,@PublishDate,@IsInternal)");
cmd.Parameters.Add(new SqlParameter("@Name", System.Data.SqlDbType.VarChar, 50));
cmd.Parameters.Add(new SqlParameter("@PublishDate", System.Data.SqlDbType.DateTime));
cmd.Parameters.Add(new SqlParameter("@IsInternal", System.Data.SqlDbType.Bit));
cmd.Parameters["@Name"].Value = book.Name;
cmd.Parameters["@PublishDate"].Value = book.PublishedDate;
cmd.Parameters["@IsInternal"].Value = book.IsInternal;

当人们报告客户端代码和SQL数据库之间的数据类型问题时,最大的错误来源是,无论出于何种原因,他们将所有内容转换为字符串。这不仅通常效率较低,而且您还依赖于至少两个转换(Type -> string和string -> Type)之间正确发生,并且通常至少有一个转换将留给默认转换函数。