我有多个表单,每个表单执行特定的任务,需要连接到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"(我将连接到的数据库)应该是不同的。
你可以采用单例方法:
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 # 35;
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。净
Dim db As DBase = DBase.GetInstance("DEMO")
Dim name As [String] = db.GetUsernameFromEmail("jsmith@contoso.com")
c # 35;
DBase db = DBase.GetInstance("DEMO");
String name = db.GetUsernameFromEmail("jsmith@contoso.com");
非常粗糙,但能完成任务。您可以更详细地说明验证、连接检查、清理和(可能的)线程安全,但我将保持示例简短。