【发布时间】:2009-08-19 09:07:55
【问题描述】:
我无法插入使用 c# 语言 DateTime.Now.ToString()
在数据类型日期时间字段中插入 sqlserver
【问题讨论】:
-
您可以将日期作为 YYYY-MM-DD 插入到 SQL Server 中,无论您的本地化如何,它每次都会起作用。
我无法插入使用 c# 语言 DateTime.Now.ToString()
在数据类型日期时间字段中插入 sqlserver
【问题讨论】:
不要将您的 DateTime 值转换为字符串。改用参数化 SQL:
string sql = "INSERT INTO Your_Table (Your_Column) VALUES (@YourParam)";
using (SqlConnection conn = new SqlConnection("..."))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("@YourParam", SqlDbType.DateTime).Value = yourDate;
conn.Open();
cmd.ExecuteNonQuery();
}
【讨论】:
您不必执行 ToString() 来插入 SQL 服务器数据库
【讨论】:
您的问题没有多大意义,但我认为您正在寻找这个:
DateTime.Now.ToString(string format)
这将以您想要的方式格式化 DateTime。
不过,您确实不应该首先将 SQL 查询构建为字符串。您应该使用参数,它允许您提供 C# 非字符串对象而不是转换后的字符串。
【讨论】: