How Do I insert Date and Time into SQL Server database in certain format? [duplicate]

陌路散爱 提交于 2020-01-06 18:07:37

问题


I am using Windows forms in C#.

I am trying to fill a table in a SQL Server database which contains DateTime column.

Now when my PC's clock format is dd-MM-yyyy and when I try to insert the data with the following query, I get an error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Code:

 SqlConnection cn = new SqlConnection("Data Source=PCN11-TOSH;Initial Catalog=mydb;Integrated Security=True");
 cn.Open();

 SqlCommand cm = new SqlCommand("Insert into Orders (Order_number, Phone, DateTime, address ) values ('" 
                  + textBox1.Text + "','" + textBox2.Text + "', '"+  DateTime.Now  +"' ,'" 
                  + textBox3.Text + "')");

 cm.Connection = cn;
 cm.ExecuteNonQuery();
 cn.Close();

But when I change my PC's clock format to yyyy-MM-dd it works fine. It seems that SQL Server only accepts yyyy-MM-dd format.

My question is : how can I insert DateTime into SQL Server column according to my PC's clock format (dd-MM-yyyy)?

Thank you


回答1:


Instead of concatenating your sql command text, use parameterized query.

It will not only protects you from sql injection, but also it uses strongly typed parameters (for example, parameter should has type of SqlDbType.DateTime to pass datetime values), thus problem will gone.

var cm = new SqlCommand("Insert into Orders (Order_number, Phone, DateTime) values (@OrderNumber, @Phone, @DateTime)");
cm.Parameters.Add("@OrderNumber", SqlDbType.VarChar);
cm.Parameters["@OrderNumber"].Value = textBox1.Text;
cm.Parameters.Add("@Phone", SqlDbType.VarChar);
cm.Parameters["@phone"].Value = textBox2.Text;
cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
cm.Parameters["@DateTime"].Value = DateTime.Now;


来源:https://stackoverflow.com/questions/34289778/how-do-i-insert-date-and-time-into-sql-server-database-in-certain-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!