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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13661933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:24:41  来源:igfitidea点击:

Insert Date And Time VB into Database Table

databasevb.netdatetime

提问by Legend-Lb

I am using a DateTimePicker to select the date, and a TextBox that has the time.

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

I am trying to insert both values into a table, but it does not work

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

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

The datecolumn is of datetimetype.

date列属于datetime类型。

The code is showing this error : conversion failed when converting datetime from character string

代码显示此错误:从字符串转换日期时间时转换失败

回答by Andrew Morton

You really don't want to be passing datetimes as strings to your database owing to cultural differences in their representations. Instead, you can pass a datetime type by using a parameter. For SQL Server you need something along the lines of

您真的不想将日期时间作为字符串传递给您的数据库,因为它们的表示形式存在文化差异。相反,您可以使用参数传递日期时间类型。对于 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

回答by David Brunow

You will need a space between the text of the two text boxes:

您将需要在两个文本框的文本之间留一个空格:

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

回答by Neolisk

Your date has to be formatted for a certain culture to be correctly inserted into a database. Or just use culture neutral strings, such as dd-MMM-yyyy.

您的日期必须针对特定区域性进行格式化才能正确插入到数据库中。或者只使用文化中性字符串,例如dd-MMM-yyyy.

Your first step is to create a DateTime from DateTimePicker1.Textand TextBox1.Text- you can use ParseExact. Then format your DateTime as .ToString("G")- check this article on MSDN for more standard formats: Standard Date and Time Format Strings

您的第一步是从DateTimePicker1.Text和创建 DateTime TextBox1.Text- 您可以使用ParseExact。然后将您的日期时间格式化.ToString("G")- 查看 MSDN 上的这篇文章以了解更多标准格式:标准日期和时间格式字符串

Similar problem is described here.

这里描述类似的问题。