在using语句中自动关闭数据库连接

时间:2018-03-27 12:48:08

标签: sql vb.net

我编写了这段代码,将我的数据写入数据库

Public Class SQL_Client

    Sub AddData(ByRef myGDI As GeneralInfo)
        Dim conStr As String = "Server=NB01009;Database=DEV_DW;Trusted_Connection=true"

        Dim query As String = String.Empty
        query = "INSERT INTO GeneralInfo(id, name, data) VALUES (@id, @name, @data)"

        Using con As SqlConnection = New SqlConnection(conStr)
            Using comm As New SqlCommand
                With comm
                    .Connection = con
                    .CommandType = CommandType.Text
                    .CommandText = query
                    .Parameters.AddWithValue("@id", myGDI.id)
                    .Parameters.AddWithValue("@name", myGDI.name)
                    .Parameters.AddWithValue("@data", "Hallo Data")
                End With
                Try
                    con.Open()
                    comm.ExecuteNonQuery()
                Catch ex As SqlException
                    Console.WriteLine(ex.Message.ToString(), "Error Message")
                End Try
            End Using

            Dim subquery As String = String.Empty
            query = "INSERT INTO FullData(GeneralInfoID, userRunID VALUES(@GeneralInfoID, @userRunID)"

            For Each myData As FullData In myGDI.data
                Using command As New SqlCommand
                    With command
                        .Connection = con
                        .CommandType = CommandType.Text
                        .CommandText = query
                        .Parameters.AddWithValue("@GeneralInfoID", myGDI.id)
                        .Parameters.AddWithValue("@userRunID", myData.userRunID)
                    End With
                    Try
                        con.Open()
                        command.ExecuteNonQuery()
                    Catch ex As SqlException
                        Console.WriteLine(ex.Message.ToString(), "Error Message")
                    End Try
                End Using
            Next

        End Using
    End Sub
End Class

由于我有一个嵌套对象,我想写入数据库(参见here)我使用了一个循环和一个seconed Using Statement。在第二个command.ExecuteNonQuery(),它得到未处理的异常:

System.INvalidOperationException: 'The connection was not closed. The connection's current state is open.'

我实际上认为在离开Using语句后,连接会自动关闭。但看起来这个假设是错误的。谁能告诉我如何正确处理这个问题?

1 个答案:

答案 0 :(得分:2)

在连接关闭之前,您要重新打开连接两次。 它将在最后End Using之后自动关闭。

删除第二个con.Open(),它应该没问题。