VB.NET连接未关闭。连接的当前状态是打开的

时间:2015-09-23 06:08:19

标签: .net vb.net

我收到了这个错误:

  

连接未关闭。连接的当前状态是打开的。

尝试从应用程序保存数据时。我正在使用VB.net和sql server 2008。

这是我的代码:

Public Function Insert(ByVal Code As String, ByVal Name As String, Optional ByVal trans As SqlTransaction = Nothing) As Boolean
    Dim iResult As Integer
    Dim arrColumn() As String = {"Code", "Name"}
    Dim arrValue() As Object = {Code, Name}

    oConn.Open()
    Dim SQLString As String = GenInsert("BNK", arrColumn, arrValue)

    Dim comm As New SqlCommand
    Try
        'iResult = SCommand.Execute(SQLString, oConn)
        If trans IsNot Nothing Then
            oConn = trans.Connection
            comm.Transaction = trans
        Else
            oConn.Open()
        End If
        comm.Connection = oConn
        comm.CommandText = SQLString
        iResult = comm.ExecuteNonQuery
    Catch ex As Exception
        Throw ex 'the error is pointed here
    Finally
        If trans Is Nothing Then
            oConn.Close()
        End If
    End Try
我错过了什么或在这里?

- 谢谢你的帮助

2 个答案:

答案 0 :(得分:1)

您正在打开连接两次。请删除oConn.Open()声明正上方的第SQLString行。

答案 1 :(得分:1)

如果oConn状态已关闭,则只打开连接。

而不是oConn.Open()使用if (oConn.State==ConnectionState.Close) then oConn.Open()