将日期和时间VB插入数据库表

时间:2012-12-01 17:40:44

标签: database vb.net date time

我正在使用DateTimePicker来选择日期,以及一个有时间的TextBox。

我正在尝试将两个值都插入到表中,但它不起作用

INSERT INTO dt (date) VALUES('" & DateTimePicker1.Text  & TextBox1.Text & "');

date列属于datetime类型。

代码显示此错误:从字符串

转换datetime时转换失败

3 个答案:

答案 0 :(得分:1)

由于其表示形式存在差异,您实际上不希望将日期时间作为字符串传递给数据库。相反,您可以使用参数传递日期时间类型。对于SQL Server,您需要符合

的内容
Dim dt As DateTime
dt = DateTimePicker1.Value.Date ' use only the date portion '
Dim tim As DateTime
If DateTime.TryParse(TextBox1.Text, tim) Then
    dt = dt + tim.TimeOfDay ' use only the time portion '
Else
    MsgBox("Could not understand the value in the time box. Using midnight.")
End If

Dim sql As String = "INSERT INTO dt (date) VALUES (@DateTime)"

Dim sqlCmd As New SqlCommand(sql, sqlConn)
sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@DateTime", .SqlDbType = SqlDbType.DateTime, .Value = dt})
'TODO: ExecuteNonQuery

答案 1 :(得分:0)

两个文本框的文本之间需要一个空格:

insert into dt (date) values('" & DateTimePicker1.Text & " " & TextBox1.Text & "')

答案 2 :(得分:0)

您的日期必须格式化,才能将某种文化正确插入数据库。或者只使用文化中性字符串,例如dd-MMM-yyyy

您的第一步是从DateTimePicker1.TextTextBox1.Text创建日期时间 - 您可以使用ParseExact。然后将日期时间格式设置为.ToString("G") - 请查看MSDN上的这篇文章,了解更多标准格式:Standard Date and Time Format Strings

类似的问题被描述为here

相关问题