1

在我的网络应用程序中出现此错误。

事务要么与当前连接无关,要么已完成。

#Region "Database Queries"
Private Shared oSqlConnection As SqlConnection
Private Shared oSqlDataAdapter As SqlDataAdapter
Private Shared oSqlCommand As SqlCommand
Private Shared oSqlTransaction As SqlTransaction

Private Shared _strCommand As String

Public Shared Property strCommand() As String
    Get
        Return _strCommand
    End Get

    Set(ByVal value As String)
        If Not InTransaction Then RollBack_Transaction()
        _strCommand = "SET DATEFORMAT mdy " & vbCrLf & value
        DbQuery()
    End Set
End Property

Protected Shared Sub DbQuery()
    'Try

    If Not InTransaction Then
        RollBack_Transaction()

        oSqlCommand = New SqlCommand(_strCommand, oSqlConnection)
    Else
        oSqlCommand = oSqlConnection.CreateCommand
        If _InTransaction_Initial Then
            oSqlConnection.Open()
            oSqlTransaction = oSqlConnection.BeginTransaction(IsolationLevel.ReadCommitted)
            _InTransaction_Initial = False
        End If

        oSqlCommand.Transaction = oSqlTransaction
        oSqlCommand.CommandText = _strCommand
        oSqlCommand.CommandTimeout = 0
    End If

    oSqlDataAdapter = New SqlDataAdapter(oSqlCommand)
    Ds = New DataSet
    oSqlDataAdapter.Fill(Ds) '**<- - - The error occurs here**'

    'Catch ex As Exception
    '    SetMessage(ex)
    '    ' MsgBox("Server: " & ServerName & vbCrLf & "User Id: " & SqlID & vbCrLf & "Password: " & SqlPassword & vbCrLf & "Database: " & MainDb)
    'End Try

    'oSqlConnection.Close()

End Sub

Private Shared _InTransaction_Initial As Boolean = False
Private Shared InTransaction As Boolean

Public Shared Sub StartTransaction()
    _InTransaction_Initial = True
    InTransaction = True
End Sub
Public Shared Sub RollBack_Transaction()
    Try
        oSqlTransaction.Rollback()
    Catch ex As Exception
    End Try
    Try
        oSqlConnection.Close()
    Catch ex As Exception
    End Try

    InTransaction = False
End Sub

Public Shared Sub Commit_Transaction()
    Try
        oSqlTransaction.Commit()
    Catch ex As Exception
    End Try
    Try
        oSqlConnection.Close()
    Catch ex As Exception
    End Try

    InTransaction = False
End Sub

Function dsCount() As Long
    Return Ds.Tables(0).Rows.Count
End Function

请参阅代码中的粗体文本。

希望听到您的积极回应。

问候,

4

1 回答 1

1

发生错误是因为您使用了Shared member variables

您可以使用共享函数,但您应该完全避免共享变量或成员。
不要在共享上下文中“保存”任何信息。这些在应用程序范围内可用,并且对于来自不同用户的不同请求可能是相同的。

在共享(静态)函数中运行数据访问操作应该没有问题。
但是拥有共享成员会导致完整性和并发性问题,使应用程序不稳定

将这些作为变量放在方法中

oSqlConnection As SqlConnection
oSqlDataAdapter As SqlDataAdapter
oSqlCommand As SqlCommand
oSqlTransaction As SqlTransaction

将解决问题。

于 2013-03-19T18:41:23.223 回答