main函数只有一个,在模块里定义,你提供的代码我看了,函数写的很不科学。用函数和子程序的原则是1:功能单一,仅完成某一项功能即可 2:函数中不要使用全程变量,即使实际上使用了全程变量,也使用传值的方式单列开。我对你的程序修改后代码如下,我是用的sql2000,模拟你的资料,建了个usertable表,里面有个admin名和admin的记录,运行通过,代码如下:
'模块里代码
Public LoginSucceeded As Boolean
'登陆成功标记
Public conn As New ADODB.Connection
Public Function OpenCn(con As Connection) As Boolean
'连接数据库
On Error Resume Next
OpenCn = False
If con.State = 1 Then
'数据库连接已经打开,设置打开标志即退出,无需重复打开数据库
OpenCn = True
Exit Function
End If
con.ConnectionTimeout = 10
SQL = "driver={sql server};server=(local);uid=sa;pwd=;Database=demo"
con.ConnectionString = SQL
con.Open
If con.State = 1 Then OpenCn = True
End Function
Public Sub cloCn(con As Connection)
'关闭数据库
On Error Resume Next
If con.State <> adStateClosed Then con.Close
Set con = Nothing
End Sub
Public Function openRs(ByVal strsql As String, rs As Recordset) As Boolean
'打开记录集
On Error Resume Next
openRs = False
If rs.State = 1 Then rs.Close
'如果记录集是打开状态则先关闭
With rs
.ActiveConnection = conn
.CursorLocation = adUseServer
'由于使用的是sql server,这里游标是adUseServer
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open strsql
End With
If rs.State = 1 Then openRs = True
End Function
Public Sub cloRs(rs As Recordset)
On Error Resume Next
If rs.State <> adStateClosed Then rs.Close
Set rs = Nothing
End Sub
'这是我写的main函数
Sub Main()
If Not OpenCn(conn) Then
MsgBox "数据库连接失败,请检查数据库", , "提示"
End
End If
login.Show
End Sub
'login里代码,我没有写info代码,你自己琢磨下
Private Sub Command1_Click()
Dim str As String, rs As New Recordset
Dim str1 As String
If Trim(Text1) = "" Or Trim(Text2) = "" Then
MsgBox "用户名或密码不能为空", , "错误提示"
Text1.SetFocus
End If
str = "select * from usertable where username='" & Trim(Text1) & "' and userpasswd='" & Trim(Text2) & "'"
If Not openRs(str, rs) Then
MsgBox "数据库记录不能打开,请检查数据库", , "错误提示"
End
End If
If Not rs.EOF Then
Info.Show
cloRs rs
Unload Me
Else
MsgBox "用户名或密码错误,请检查", , "错误提示"
Text1.SetFocus
End If
End Sub