date time conversion problem when inserting data into sql database

穿精又带淫゛_ 提交于 2019-12-10 12:16:26

问题


I used to query:

Dim a As String
a = "INSERT INTO tblVisitor(Name, Sex, TimeIn, EnterDate)
     VALUES('"& txtName.Text &"', '"& cboSex.Text &"', '"& Now() &"', '"& DateTime.Parse(cboEnterDate.Text) &"')"

myCommand = New SqlCommand(a, myConnection)
myCommand.ExecuteNonQuery()
........................................

Which cboEnterDate is my DateTime Picker. Then I got the message:

Conversion failed when converting date time from character string.

Please help.


回答1:


By constructing a string, you a) open yourself to SQL injection, and b) end up converting strings to datetimes to strings to datetimes.

If, instead, you use parameters:

Dim a As String
a = "INSERT INTO tblVisitor(Name, Sex, TimeIn, EnterDate)
     VALUES(@Name, @Sex, @TimeIn, @EnterDate)"

myCommand = New SqlCommand(a, myConnection)
myCommand.Parameters.AddWithValue("@Name",txtName.Text)
myCommand.Parameters.AddWithValue("@Sex",cboSex.Text)
myCommand.Parameters.AddWithValue("@TimeIn",DateTime.Now)
myCommand.Parameters.AddWithValue("@EnterDate",DateTime.Parse(cboEnterDate.Text))
myCommand.ExecuteNonQuery()

Which only performs a single conversion of string to datetime. Although, if cboEnterDate is a DateTimePicker, you can avoid treating it as a string at all:

myCommand.Parameters.AddWithValue("@EnterDate",cboEnterDate.Value)



回答2:


Look up using SQL Parameters. The code you are using now is not only prone to parsing issues w/r/t date formats, it is vulnerable to SQL injection attacks. Creating SQL statements via string concatenation is just a really, really bad idea.




回答3:


Change Now() to Now.ToShortTimeString That should fix the problem.

Edit: Oops and the DateTime.Parse(cboEnterDate.Text) add .ToShortDate to the end.




回答4:


When you use DateTime.Parse(cboEnterDate.Text) it parses the string into a datetime object. You should send the string cboEnterDate.Text directly and let the SQL server do the parsing



来源:https://stackoverflow.com/questions/6530536/date-time-conversion-problem-when-inserting-data-into-sql-database

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