如何在整个项目中处理数据库连接

时间:2015-08-24 06:54:35

标签: vb.net oop database-connection

我在模块中创建了一个函数来连接到Windows应用程序的数据库

Imports System.Data.SqlClient
Module mod_main
Public Function connectDB() As SqlConnection
        Dim Connection As New SqlConnection
        Try
            If Connection.State = ConnectionState.Open Then
                Connection.Close()
            End If
            If IntegratedSecurity Then
                Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;Integrated Security=True"
            Else
                Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;User ID='" & usr & "';Password='" & pwd & "'"
            End If
            Connection.Open()
            Return Connection
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Function
End Module

我有很多函数和类使用了大量的db活动,因为我使用了上面提到的连接函数。例如:

 Public Sub FillComboBox(ByVal ComboBox As C1.Win.C1List.C1Combo, ByVal Query As String, ByVal DisplayMember As String, ByVal ValueMember As String)
        Dim SourceDataSet As New DataSet
        Dim adapter As New SqlDataAdapter(Query, connectDB) /*Assigning connection here */
        adapter.Fill(SourceDataSet)
        ComboBox.DataSource = SourceDataSet.Tables(0)
        ComboBox.ColumnHeaders = False
        ComboBox.ColumnWidth = 0
        ComboBox.ExtendRightColumn = True
        ComboBox.DisplayMember = DisplayMember
        ComboBox.ValueMember = ValueMember
    End Sub

由于我是编程的初学者,我的问题是,这是处理数据库连接的正确方法吗?

1 个答案:

答案 0 :(得分:0)

我建议您进行以下更改:

  1. Connection公开为全球可访问性
  2. config file中保存连接字符串并从那里访问
  3. 仅在没有可用连接时才需要关闭并重新打开连接打开连接
  4.   

    在您的情况下,它始终在函数创建新连接时   因为你在声明和初始化连接内部而调用了   功能。所以检查连接状态意味着更少:

    所以你的功能如下:

    public Connection As New SqlConnection
    Public Function connectDB() As SqlConnection
          Try
                Dim Constr As String =""
                If IntegratedSecurity Then
                   Constr = ConfigurationManager.AppSetting("IconnectionString")
                Else
                   Constr  = ConfigurationManager.AppSetting("connectionString")
                End If
                If Connection Is Nothing Then
                    Connection = New SqlConnection(Constr)
                End If
                If Connection.State <> ConnectionState.Open Then
                  Connection.Open()
                End If           
                Return Connection
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
    End Function