转换sql以使用事务

时间:2016-07-28 06:43:46

标签: vb.net

我想将当前的sql转换为使用事务功能。到目前为止,我做了原始的sql函数,如下所示。如何转换它以使用该函数中的事务?

Public Function GetAllByKatId(Id As Integer) As Object
    Dim result As Object
    Dim dt As New DataTable
    dt.Clear()
    Using cnn As New SqlConnection(strcon)
        cnn.Open()
        Using dad As New SqlDataAdapter("SELECT * FROM tbGet WHERE ID=@id", cnn)
            dad.SelectCommand.Parameters.Add(New SqlParameter("@id", Id))
            dad.Fill(dt)

            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                result = dt
            Else
                result = Nothing
            End If
        End Using
        cnn.Close()
    End Using
    Return result
End Function

1 个答案:

答案 0 :(得分:0)

从SqlConnection生成事务 - 将其应用于SqlDataAdapter中的select,update,insert,delete命令,然后根据需要调用Commit / Rollback。

Public Function GetAllByKatId(Id As Integer) As Object
    Dim result As Object
    Dim dt As New DataTable
    dt.Clear()
    Using cnn As New SqlConnection(strcon)
        cnn.Open()
        dim trans as SqlTransaction
        trans = cnn.BeginTransaction()
        Using dad As New SqlDataAdapter("SELECT * FROM tbGet WHERE ID=@id", cnn)
            dad.SelectCommand.Parameters.Add(New SqlParameter("@id", Id))
            dad.SelectCommand.Transaction = trans
            dad.Fill(dt)

            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                trans.Commit()
                result = dt
            Else
                trans.Rollback()
                result = Nothing
            End If
        End Using
        cnn.Close()
    End Using
    Return result
End Function