将数据插入sql数据库时的日期时间转换问题 [英] date time conversion problem when inserting data into sql database

查看:158
本文介绍了将数据插入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是我的DateTime选择器。然后我得到消息:

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

Conversion failed when converting date time from character string.

请帮助。

推荐答案

通过构造一个字符串,您a)接受SQL注入,然后b)最终将字符串转换为日期时间,将字符串转换为日期时间。

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()

仅将字符串转换为日期时间。虽然,如果 cboEnterDate DateTimePicker ,您完全可以避免将其视为字符串:

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)

这篇关于将数据插入sql数据库时的日期时间转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆