好吧,您采用单例方法:
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");
非常粗糙,但可以完成工作。您可以通过验证、连接检查、清理和(可能)线程安全来获得更详细的信息,但我将保持示例简短而有趣。