在 vb.net 中插入当前日期时间(DateTime to String Conversion)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24300246/
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
Inserting the current datetime in vb.net(DateTime to String Conversion)
提问by thilim9
I'm suppose to enter datatime to the database by passing this query
我想通过传递这个查询将数据时间输入到数据库中
Dim regDate As DateTime = DateTime.Now
Dim strDate As String = regDate.ToString("yyyyMMddHHmmss")
I pass the "strDate" to the query,data type of my database table is datetime
我将“strDate”传递给查询,我的数据库表的数据类型是日期时间
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & regDate & "')")"
but it's getting error saying that
但它得到错误说
conversion failed when converting date and/or time from character string.
从字符串转换日期和/或时间时转换失败。
Help me to solve this problem
帮我解决这个问题
回答by HengChin
Dim regDate As DateTime = DateTime.Now
Dim strDate As String = regDate.ToString("yyyy-MM-dd HH:mm:ss")
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & strDate & "')")"
回答by Nagaraj S
you have to pass strDatein query.Always use paremeterized query to avoid SQL injection
您必须传入strDate查询。始终使用参数化查询来避免 SQL 注入
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & strDate & "')")"
回答by Exterion
May this works for you, at least it works for me on an acces db
可能这对你有用,至少它对我的访问数据库有用
Try
Dim cn As New OleDbConnection("your conection string here")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
Dim sSQL As String = "insert into UserInfo(Date) values(@d1)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
Dim date As OleDbParameter = New OleDbParameter("@d1", OleDbType.Date, 15)
date.Value = DateTimePicker1.Text.ToString()
cmd.Parameters.Add(date)
If cmd.ExecuteNonQuery() Then
cn.Close()
MsgBox("successfully... ", MsgBoxStyle.Information, "Record Saved")
Else
MsgBox("failed... ", MsgBoxStyle.Critical, "Registration failed")
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Error")
Exit Sub
End Try
i hope this helps you,
我希望这可以帮助你,
regards Tom
问候汤姆

