我正在从SQL数据库中读取并根据我检查的字段,我需要更新同一个表中的其他字段。我循环遍历数据集并尝试在循环时发回UPDATE。它在我的TEST表上工作但不适用于我的生产表。当我执行" ExecuteNonQuery"命令,我得到超时过期错误。如果我实际关闭第一个连接,然后调用ExecuteNonQuery,它会立即运行。
这是代码......
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sqlConn As New SqlConnection
Dim sqlComm As New SqlCommand
Dim sqlDR As SqlDataReader
sqlConn.ConnectionString = "Data Source=10.2.0.87;Initial Catalog=Inbound_Orders_DB;User ID=xxxxx;Password=xxxxxx;"
sqlConn.Open()
sqlComm.CommandText = "SELECT * FROM RH_Orders where Order_DateTime is NULL ORDER by Order_Date DESC"
sqlComm.Connection = sqlConn
sqlDR = sqlComm.ExecuteReader
If sqlDR.HasRows Then
While sqlDR.Read
If Trim(sqlDR("Order_Date")) <> "" Then
Dim order_Date As String = Trim(sqlDR("Order_Date"))
Dim order_DateTime As String = ""
If Len(order_Date) = 14 Then
order_DateTime = order_Date.Substring(0, 4) & "-" & order_Date.Substring(4, 2) & "-" & order_Date.Substring(6, 2) & " "
order_DateTime = order_DateTime & order_Date.Substring(8, 2) & ":" & order_Date.Substring(10, 2) & ":" & order_Date.Substring(12, 2)
Dim myId As String = sqlDR("ID")
Dim sqlConn2 As New SqlConnection
Dim sqlComm2 As New SqlCommand
sqlConn2.ConnectionString = "Data Source=10.2.0.87;Initial Catalog=Inbound_Orders_DB;User ID=xxxx;Password=xxxx;"
sqlConn2.Open()
sqlComm2.CommandText = "UPDATE [RH_Orders] SET order_DateTime = '" & order_DateTime & "' WHERE ID=" & myId
sqlComm2.Connection = sqlConn2
sqlComm2.ExecuteNonQuery()
sqlConn2.Close()
End If
End If
End While
End If
End Sub
End Class
答案 0 :(得分:1)
使用参数化查询并且不要连接字符串,然后使用SqlParameter
和SqlDbType.Datetime
并分配实际DateTime
而不是格式化字符串。
但也许在这里用DataTable
填充SqlDataAdapter.Fill(table)
,循环表Rows
,更改每个DataRow
并使用{{}会更有效率1}}在循环后发送一批中的所有更改。不需要SqlDataAdapter.Update(table)
循环。
例如(未经测试):
SqlDataReader
旁注:而不是建立一个新字符串&#34; 2017-01-31&#34;来自&#34; 20170131&#34;你也可以使用Using con = New SqlConnection("Data Source=10.2.0.87;Initial Catalog=Inbound_Orders_DB;User ID=xxxxx;Password=xxxxxx;")
Using da = New SqlDataAdapter("SELECT * FROM RH_Orders where Order_DateTime is NULL ORDER by Order_Date DESC", con)
da.UpdateCommand = New SqlCommand("UPDATE RH_Orders SET order_DateTime = @order_DateTime WHERE ID = @Id", con)
da.UpdateCommand.Parameters.Add("@order_DateTime", SqlDbType.DateTime).SourceColumn = "order_DateTime"
Dim table = New DataTable()
da.Fill(table)
For Each row As DataRow In table.Rows
Dim orderDate = row.Field(Of String)("Order_Date")
Dim orderDateTime As DateTime
If DateTime.TryParse(orderDate.Substring(0, 4) & "-" & orderDate.Substring(4, 2) & "-" & orderDate.Substring(6, 2), orderDateTime) Then
row.SetField("order_DateTime", orderDateTime)
End If
Next
da.Update(table)
End Using
End Using
:
DateTime.TryParseExact