使用c#在sql数据库中插入datetime值

32 c# sql datetime

如何将日期时间值插入到SQL数据库表中,其中列的类型是datetime?

Tho*_*mar 83

以下应该工作,是我的建议(参数化查询):

DateTime dateTimeVariable = //some DateTime value, e.g. DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)

  • +1我很惊讶这里有多少答案建议非参数化查询.使用参数化查询不仅可以解决SQL注入问题,还可以解决SQL Server日期本地化问题. (11认同)

Res*_*hma 18

 DateTime time = DateTime.Now;              // Use current time
 string format = "yyyy-MM-dd HH:mm:ss";    // modify the format depending upon input required in the column in database 
 string insert = @" insert into Table(DateTime Column) values ('" + time.ToString(format) + "')"; 
Run Code Online (Sandbox Code Playgroud)

并执行查询. DateTime.Now是插入当前日期时间..

  • yyyy-MM-dd HH:MM:ss实际上是MONTH而不是分钟.它应该是'mm' (6认同)

小智 8

使用格式yyyy-mm-dd hh:mm:ss更为标准(IE:2009-06-23 19:30:20)

使用它你不必担心日期的格式(MM/DD/YYYY或DD/MM/YYYY).它将适用于所有这些.

  • mm的月份将类似于MM,否则它将显示分钟而不是月份。 (3认同)

atf*_*rgs -10

INSERT INTO <table> (<date_column>) VALUES ('1/1/2010 12:00')
Run Code Online (Sandbox Code Playgroud)