我有一个Employee类,我在其中调用数据库连接模块进行查询。
我得到了"编译错误:期望的函数或变量",我不理解,因为我在表单的顶部设置了empObj
。
我想返回Employee.getEmployee方法的值。有人能告诉我如何从我的表格中调用员工类吗?我必须先导入类吗?我认为VB6不支持Imports
关键字。
这是我的表格:
Option Explicit
Private empObj As New Employee
Private Sub Form_Load()
'For testing only
MsgBox (empObj.getEmployee)
End Sub
这是我的课:
Public Sub getEmployee()
'ConnectSQL is a database connection
return ConnectSQL
End Sub
这就是模块:
Public Function ConnectSQL()
Set SQLMyconn = New ADODB.Connection
Set SQLRecset = New ADODB.Recordset
SQLMyconn.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"
End Function
您想要做的事情的基本外壳是这样的:
Option Explicit
Private empObj As Employee
Private Sub Form_Load()
Set empObj = New Employee
MsgBox empObj.getEmployee
End Sub
Public Function getEmployee() As String
getEmployee = ConnectSQL
End Function
Public Function ConnectSQL() As String
Set SQLMyconn = New ADODB.Connection
Set SQLRecset = New ADODB.Recordset
SQLMyconn.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"
ConnectSQL = "data from your DB lookup"
End Function
几乎每一行都与您发布的内容不同,所以请仔细查看代码。
编辑:
基于注释,以下是如何修改代码以返回连接对象:
Option Explicit
Private empObj As Employee
Private Sub Form_Load()
Set empObj = New Employee
MsgBox empObj.getEmployee
Dim MyConnection As ADODB.Connection
Set MyConnection = ConnectSQL()
'you can grab and use the connection in your form, too.
End Sub
Public Function getEmployee() As String
Dim MyConnection As ADODB.Connection
Set MyConnection = ConnectSQL()
'use the connection to grab data
getEmployee = "data from your DB lookup"
End Function
Public Function ConnectSQL() As ADODB.Connection
Set ConnectSQL = New ADODB.Connection
ConnectSQL.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"
End Function
不要忘记在你完成连接后关闭它。总结一下变化:
- empObj-应该分别声明和实例化对象
- MsgBox-不需要((
- 函数与子-第一个返回数据,第二个不返回数据。请确保声明函数的返回类型
- return-此语句已过时,无法执行您想要的操作。相反,为函数的名称指定一个值