为什么在将 date.today 提交到日期时间列时,sql server 会给出转换错误?
每次尝试向 sql server 提交日期值时,我都会收到转换错误。 sql server 中的列是日期时间,在 vb 中我使用 Date.today 传递给我的参数化查询。 我不断收到 sql 异常
从字符串转换日期时间时,
转换失败。这是代码
Public Sub ResetOrder(ByVal connectionString As String)
Dim strSQL As String
Dim cn As New SqlConnection(connectionString)
cn.Open()
strSQL = "DELETE Tasks WHERE ProjID = @ProjectID"
Dim cmd As New SqlCommand(strSQL, cn)
cmd.Parameters.AddWithValue("ProjectID", 5)
cmd.ExecuteNonQuery()
strSQL = "INSERT INTO Tasks (ProjID, DueDate, TaskName) VALUES " & _
" (@ProjID, @TaskName, @DueDate)"
Dim cmd2 As New SqlCommand(strSQL, cn)
cmd2.CommandText = strSQL
cmd2.Parameters.AddWithValue("ProjID", 5)
cmd2.Parameters.AddWithValue("DueDate", Date.Today)
cmd2.Parameters.AddWithValue("TaskName", "bob")
cmd2.ExecuteNonQuery()
cn.Close()
DataGridView1.DataSource = ds.Projects
DataGridView2.DataSource = ds.Tasks
End Sub
任何想法将不胜感激。
I am getting a conversion error every time I try to submit a date value to sql server. The column in sql server is a datetime and in vb I'm using Date.today to pass to my parameterized query. I keep getting a sql exception
Conversion failed when converting datetime from character string.
Here's the code
Public Sub ResetOrder(ByVal connectionString As String)
Dim strSQL As String
Dim cn As New SqlConnection(connectionString)
cn.Open()
strSQL = "DELETE Tasks WHERE ProjID = @ProjectID"
Dim cmd As New SqlCommand(strSQL, cn)
cmd.Parameters.AddWithValue("ProjectID", 5)
cmd.ExecuteNonQuery()
strSQL = "INSERT INTO Tasks (ProjID, DueDate, TaskName) VALUES " & _
" (@ProjID, @TaskName, @DueDate)"
Dim cmd2 As New SqlCommand(strSQL, cn)
cmd2.CommandText = strSQL
cmd2.Parameters.AddWithValue("ProjID", 5)
cmd2.Parameters.AddWithValue("DueDate", Date.Today)
cmd2.Parameters.AddWithValue("TaskName", "bob")
cmd2.ExecuteNonQuery()
cn.Close()
DataGridView1.DataSource = ds.Projects
DataGridView2.DataSource = ds.Tasks
End Sub
Any thoughts would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
或
代替
Try
Or
Instead of
可能是应用程序和 SQL Server 之间的区域设置不同造成的问题。
尽管它不能解决根本问题,但避免这种情况的直接方法是显式格式化传递给 SQL 的日期
编辑:
我更仔细地阅读了您的代码:您的参数和值的顺序不同。尝试:
Could be an issue with different regional settings between your application and SQL server.
Although it doesn't resolve the underlying issue, a straight-forward way to avoid this is by explicitly formatting the date you pass to SQL
EDIT:
I read your code more carefully: you've got your parameters and values in different orders. Try:
参数顺序错误。哎哟!
@TaskName 和 @DueDate 已交换。我相信以上所有建议都是正确的。
Parameters were in the wrong order. Doh!
@TaskName and @DueDate were swapped. I believe all of the above suggestion are correct.