2015-08-24 133 views
0

我有一個模塊中創建了一個功能完整的項目數據庫連接連接到數據庫的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 

我有這麼多的功能和類使用的數據庫活動,過多的我使用function.For exmample上述連接:

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 

因爲我在編程我的問題是初學者的是,這是處理數據庫連接的正確方法?

回答

0

我建議你作如下修改:

  1. 使Connection公共全球可訪問
  2. 保存連接字符串中config file,並從那裏訪問它
  3. 不必關閉並重新打開連接開放僅在沒有可用連接時連接

在你的情況下,所有這一切都會創建一個新的連接,因爲你正在聲明和初始化 函數中的連接,所以調用該函數時會調用 。因此檢查連接狀態少義:

所以你的函數看起來像以下:

+0

將檢查..... – gabriele