sql数据库插入数据时日期时间转换问题
我曾经查询过:
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()
........................................
哪个 cboEnterDate 是我的日期时间选择器。然后我收到消息:
Conversion failed when converting date time from character string.
请帮忙。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过构造字符串,您 a) 向 SQL 注入开放,并且 b) 最终将字符串转换为日期时间。
相反,如果您使用参数:
则仅执行一次字符串到日期时间的转换。虽然,如果
cboEnterDate
是 DateTimePicker,您可以完全避免将其视为字符串: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:
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:使用 SQL 参数查找。您现在使用的代码不仅容易出现日期格式解析问题,而且容易受到 SQL 注入攻击。通过字符串连接创建 SQL 语句是一个非常非常糟糕的主意。
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.
将 Now() 更改为 Now.ToShortTimeString 这应该可以解决问题。
编辑:哎呀,DateTime.Parse(cboEnterDate.Text) 将 .ToShortDate 添加到末尾。
Change Now() to Now.ToShortTimeString That should fix the problem.
Edit: Oops and the DateTime.Parse(cboEnterDate.Text) add .ToShortDate to the end.
当您使用 DateTime.Parse(cboEnterDate.Text) 时,它将字符串解析为日期时间对象。您应该直接发送字符串
cboEnterDate.Text
并让SQL服务器进行解析When you use
DateTime.Parse(cboEnterDate.Text)
it parses the string into a datetime object. You should send the stringcboEnterDate.Text
directly and let the SQL server do the parsing