con.close与con=nothing的区别

con.close()只是关闭了连接,并没有清除con,要想再使用它需要con.open()再重新开启就可以了。

ADO中用的是传址,所以如果con=nothing就表示清除了con,外部函数就用不了了。如果想还使用连接,就必须再创建一个con对象,然后再打开使用。

今日做系统的时候遇到了这个问题:

首先,先执行了下面的代码

 

Sub AddQuitRecord(ByVal backcard As Entry.BackCard)
        Dim sql As String = "Insert into backcard values('" & backcard.CardID & "','" & backcard.BackDate & "','" & backcard.BackTime & "','" & backcard.BackCash & "','" & backcard.Actor & "')"
        Dim sqlcmd As SqlCommand = New SqlCommand(sql, con)
        Try
            con.Open()
            sqlcmd.ExecuteReader()
            con.Close()
        Catch ex As Exception

        End Try
        If Not IsNothing(con) Then
            con.Close()
            con = Nothing
        End If
    End Sub

由于上面代码中已经执行了con=Nothing,导致下面的运行到con.open()的时候,就会报错。

在这里,我们没有必要清楚con,所以我们需要关闭连接就可以了,所以正解是将上面的con=nothing删去。在执行到下面代码是就不会报错了。

 Public Function QuitCard(ByVal quitcardd As Entry.BackCard) As Boolean
        Dim sql As String = "Update card set static='" & False & "' where cardnumber='" & quitcardd.CardID & "'"
        Dim sqlcmdd As SqlCommand = New SqlCommand(sql, con)
        Try
            con.Open()
            Return sqlcmdd.ExecuteNonQuery > 0
        Catch ex As Exception
            Return False
        End Try
        If Not IsNothing(con) Then
            con.Close()
        End If
    End Function



 

posted on 2012-01-29 10:08  刘正权的博客  阅读(330)  评论(0编辑  收藏  举报