2015-11-15 34 views
0

任何人都可以幫助我如何爲變量objusername和objpassword的子登錄被子類Class_Initialize識別?我試過這個,但它不起作用。如何使用類初始化vb6連接到SQL服務器?

private cn as ADODB.Connection 
private record As ADODB.Recordset 

private objusername as variant 
private objpassword as variant 

Public Sub login(objuser As Variant, objpass As Variant) 
Set cn = New ADODB.Connection 
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost\SQLExpress;Initial Catalog=bdd;User ID=" & objusername & ";Password=" & objpassword & "" 
cn.Open 
    If cn.State = adStateOpen Then 
     MsgBox "welcome", vbOKOnly, "connexion" 
    End If 
end sub 


Private Sub Class_Initialize() 
On Error GoTo erreur 
Set cn = New ADODB.Connection 
Set record = New ADODB.Recordset 
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost\SQLExpress;Initial Catalog=bdd;User ID='" & objusername & "';Password='" & objpassword & "'" 
cn.Open 
Exit Sub 
erreur: 
    If Err.Number = -2147217843 Then 
     MsgBox "connection failed" 
    End If 
End Sub 

和我這樣稱呼類,但我總是有錯誤。

Private Sub CmdOK_Click() 
dim x as class1 
set x = new class1 
x.Login text1,text2 
End Sub 

我該如何解決這個問題。

回答

3

Class_Initialize當你調用new class1將執行,因爲這是你叫Login之前Class_Initialize代碼中有不知道的用戶名和密碼。

Connect在Login代替:

private cn as ADODB.Connection 
private record As ADODB.Recordset 

private objusername as variant 
private objpassword as variant 

Public Sub login(objuser As Variant, objpass As Variant) 
    objusername = objuser 
    objpassword = objpass 

    Set cn = New ADODB.Connection 
    cn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost\SQLExpress;Initial Catalog=bdd;User ID=" & objusername & ";Password=" & objpassword & "" 
    cn.Open 
    ... 
end sub 

Private Sub Class_Initialize() 
End Sub 

如果你想,當你創建的Class1實例的模塊,這是缺乏構造最接近的替代方法在使用工廠函數來連接。

public function CreateAndLogin(objuser As Variant, objpass As Variant) as class1 
    set CreateAndLogin= new Class1 
    CreateAndLogin.login bjuser, objpass 
end function 

調用

Dim cls as Class1 
set cls = CreateAndLogin(text1, text2) 
+0

您可以詳細地顯示代碼給我聽聽。我在講英語時遇到困難 爲什麼類初始化爲空?我有很多的子和功能在class1上,這取決於類初始化 謝謝你的進步 –

相關問題