0

我有多个表单,每个表单都执行需要连接到 MySQL 服务器的特定任务。
在每种形式上,都声明了这些:

Imports MySql.Data.SqlClient

Dim myConnObj As New MySqlConnection

我像这样使用它们:

myConnObj = New MySqlConnection()
myConnObj.ConnectionString = "Server=" & db_Server & ";Database=" & dbase & ";UID= & "db_UserID & ";PWD=" & db_Password
myConnObj.Open()

''Things to do here

myConnObj.Close

我想将此过程转换为一个类以最小化代码,并且它应该可以通过所有形式使用,但我不知道从哪里开始。虽然我已经在 VB 中创建了一个名为 clsConnect.vb 的空类,但
请注意“dbase”(我将连接到的数据库)应该是不同的。
提前致谢。

4

1 回答 1

0

好吧,您采用单例方法:

VB.NET:

Public Class DBase
    #Region "Singleton"

    Private Shared instances As New Dictionary(Of [String], DBase)()
    Public Shared Function GetInstance(dbname As [String]) As DBase
        If Not instances.ContainsKey(dbname) Then
            instances(dbname) = New DBase(dbname)
        End If
        Return instances(dbname)
    End Function

    #End Region

    Private connection As MySqlConnection

    Private Sub New(dbase As [String])
        Me.connection = New MySqlConnection()
        Me.connection.ConnectionString = "...connection string implementing dbase..."
        Me.connection.Open()
    End Sub

    Protected Overrides Sub Finalize()
        Try
            Me.connection.Close()
        Finally
            MyBase.Finalize()
        End Try
    End Sub

    #Region "Database Methods"

    ' add the various method calls to the database here.

    #End Region
End Class

'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: @telerik, @toddanglin
'Facebook: facebook.com/telerik
'=======================================================

C#

public class DBase
{
  #region Singleton

  private static Dictionary<String, DBase> instances = new Dictionary<String, DBase>();
  public static DBase GetInstance(String dbname)
  {
    if (!instances.ContainsKey(dbname))
    {
      instances[dbname] = new DBase(dbname);
    }
    return instances[dbname];
  }

  #endregion

  private MySqlConnection connection;

  private DBase(String dbase)
  {
    this.connection = new MySqlConnection();
    this.connection.ConnectionString = "...connection string implementing dbase...";
    this.connection.Open();
  }

  ~DBase()
  {
    this.connection.Close();
  }

  #region Database Methods

  // add the various method calls to the database here.

  #endregion
}

然后你可以从任何地方访问它,并调用它:

VB.NET

Dim db As DBase = DBase.GetInstance("DEMO")
Dim name As [String] = db.GetUsernameFromEmail("jsmith@contoso.com")

C#

DBase db = DBase.GetInstance("DEMO");
String name = db.GetUsernameFromEmail("jsmith@contoso.com");

非常粗糙,但可以完成工作。您可以通过验证、连接检查、清理和(可能)线程安全来获得更详细的信息,但我将保持示例简短而有趣。

于 2013-04-26T17:08:33.930 回答