0

私はvb.netの初心者ですが、SQL接続コマンドを再利用する方法はありますか?

これが私のmain.vbのコードです:

 Dim ServerString As String = "Server=localhost;User Id=root;Password=;Database=pos"
 Dim SQLConnection As MySqlConnection = New MySqlConnection

 Private Sub Main_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    SQLConnection.ConnectionString = ServerString

    Try
        If SQLConnection.State = ConnectionState.Closed Then
            SQLConnection.Open()
        Else
            SQLConnection.Close()
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

これを他のクラスで使用したいので、このコードをすべての形式で書き直したくありません。どんな助けでも本当にありがたいです。ありがとう。

4

2 に答える 2

3

通常、接続(またはその他の管理されていないリソース)を再利用することはお勧めできません。できるだけ早く処分する必要があります。

ただし、デフォルトでADO.NET接続プールを使用しているため、とにかく常に新しい接続を作成しても問題はありません。したがって、新しい物理接続を作成(および開く)することはありません。実際には、プールを閉じたり破棄したりするときに、接続が別の場所で再利用可能であることをプールに伝えているだけです。また、開いたときは他の場所では使用できないため、常に閉じることが重要です。

したがって、常にUsing-statementを使用してください。

Public Shared Function GetColumn1(column2 As Int32) As String
    Dim sql = "SELECT Column1 From dbo.tableName WHERE Column2=@Column2 ORDER BY Column1 ASC"
    Using con = New SqlConnection(connectionString)
        Using cmd = New SqlCommand(sql, con)
            cmd.Parameters.AddWithValue("@Column2", column2)
            Try
                con.Open()
                Using rd = cmd.ExecuteReader()
                    If rd.Read() Then
                        Dim Column1 As String = rd.GetString(0)
                        Return Column1
                    Else
                        Return Nothing
                    End If
                End Using
            Catch ex As Exception
                ' log the exception here or do not catch it '
                ' note that you don't need a Finally to close the connection '
                ' since a Using-Statement disposes the object even in case of exception(which also closes a connection implicitely)
            End Try
        End Using
    End Using
End Function

上記は、何も再利用してはならないことを示すためのサンプルメソッドです。

于 2013-02-05T16:48:21.640 に答える
1

これが私が普段行っていることです。ConnectDB などのクラスを作成し、このクラス内に GetConnection などのメソッドを作成します。コードは次のとおりです。

Imports System.Data
Imports System.Data.SqlClient

Public Class ConnectDB

    Public Shared Function GetConnection() As SqlConnection
        Dim dbConnString As String = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
        Return New SqlConnection(dbConnString)
    End Function
End Class


Then from the method that needs a connection to the database, I call this function.  Here is a sample code:

Imports System.Data.SqlClient

Public Class EmployeeDB

    Public Shared Function GetEmployees() As List(Of Employee)
        Dim con As SqlConnection = ConnectDB.GetConnection()
        Dim selectStmt As String = "SELECT * FROM Employees"
        Dim selectCmd As New SqlCommand(selectStmt, con)
        Dim employees As New List(Of Employee)

        Try
            con.Open()
            Dim reader As SqlDataReader = selectCmd.ExecuteReader()
            Do While reader.Read
                Dim employee as New Employee

                employee.LastName = reader("LastName").ToString
                employee.FirstName = reader("FirstName").ToString
                ...
                employees.Add(employee)
            Loop
            reader.Close()
         Catch ex As Exception
             Throw ex
         Finally
             con.Close()
         End Try
         Return employees
    End Function
End Class

selectStmt上記のティムの例と同じように、文字列を変更してフィルター条件、パラメーター、および並べ替え順序を含めselectCmd.Parameters.AddWithValue("@<parameterName>", value)、パラメーターごとに含めることもできます。

于 2013-02-06T00:55:30.387 に答える