是否可以先读取 HasRow,然后再更新? 这是我到目前为止尝试过的代码:
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlcmd As New MySqlCommand("SELECT * FROM tbl_online_attendance where employees_id = '" & lvRealAtt.Items(itms).SubItems(0).Text & "' and in_time = '" & lvRealAtt.Items(itms).SubItems(1).Text & "' ", conn)
Dim dr As MySqlDataReader
dr = sqlcmd.ExecuteReader
If dr.HasRows Then
Dim query As String
query = "UPDATE tbl_online_attendance SET out_time = '" & lvRealAtt.Items(itms).SubItems(2).Text & "' where employees_id = '" & lvRealAtt.Items(itms).SubItems(0).Text & "' and in_time = '" & lvRealAtt.Items(itms).SubItems(1).Text & "' "
sqlcmd.Connection = conn
sqlcmd.CommandText = query
sqlcmd.ExecuteNonQuery() 'It error in this part
Else
End If
但它给了我错误说:
There is already an open DataReader associated with this Connection which must be closed first
请避免评论Use Parameters Your code is Prone to SQL injection attack
如果将连接保留在使用连接的方法的本地,则不必检查连接状态。需要尽快关闭和释放连接和命令等数据库对象。 即使出现错误,Using...End Using
块也会为您解决这个问题。在直接在.Execute...
之前不要打开连接。
当您只需要计数时,不要下拉数据。.ExecuteScalar
返回结果集第一行的第一列,在本例中为 Count。如果你有一个大表,你需要查看如果存在,它会在找到匹配项时停止,而计数会查看整个表。
始终使用参数。切勿连接字符串来构建 sql 查询,以避免 sql 注入。我不得不猜测参数的数据类型。检查数据库以获取实际类型并相应地调整代码。
Private Sub OPCode(ByVal itms As Integer)
Dim RowCount As Integer
Using conn As New MySqlConnection("Your connection string"),
sqlcmd As New MySqlCommand("SELECT Count(*) FROM tbl_online_attendance where employees_id = @id and in_time = @inTime;", conn)
sqlcmd.Parameters.Add("@id", MySqlDbType.Int32).Value = CInt(lvRealAtt.Items(itms).SubItems(0).Text)
sqlcmd.Parameters.Add("@inTime", MySqlDbType.String).Value = lvRealAtt.Items(itms).SubItems(1).Text
conn.Open()
RowCount = CInt(sqlcmd.ExecuteScalar)
If RowCount > 0 Then
sqlcmd.CommandText = "UPDATE tbl_online_attendance SET out_time = @outTime where employees_id = @id and in_time = @inTime;"
sqlcmd.Parameters.Add("@outTime", MySqlDbType.String).Value = lvRealAtt.Items(itms).SubItems(2).Text
sqlcmd.ExecuteNonQuery()
End If
End Using
End Sub
每个 SqlDataReader 都需要关闭,然后才能执行另一个查询。 因此,我建议您将SQLreader和更新查询分开,将读取器放入布尔函数中,以检查具有这些参数的行是否存在。
Private Function HasRow(ByVal employeeid As Integer, ByVal date as DateTime) As Boolean
HasRow = False
Dim reader As SqlDataReader
'do select query here
'use the if reader.Read if you want to
HasRow = reader.HasRows
reader.Close()
End Function
在更新之前调用该函数,如果为 True,则继续更新。假设我们将其放入更新子中。
Private Sub Update()
If HasRows(parameters here) Then
'update query here
End If
End Sub