关于VB连接数据库的问题

来源:百度知道 编辑:UC知道 时间:2024/05/24 08:44:17
在模块的代码::
Option Explicit

Public Conn As New ADODB.Connection
Public Rs As ADODB.Recordset
Public Sql As String

Public Function LandMDB(ByVal vFile As String) As String
On Error Resume Next
Sql = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & vFile & ";Persist Security Info=False"
Conn.Open Sql
If Err <> 0 Then LandMDB = "连接数据库错误,请检查[ " & vFile & " ]是否存在。"
End Function

要窗体的代码:
Private Sub Form_Load()
Dim ErrInfo As String

ErrInfo = LandMDB(App.Path & "\db1.mdb")
If Len(ErrInfo) <> 0 Then MsgBox ErrInfo, vbOKOnly + vbCritical, "载入数据库错误"

Set Rs = New ADODB.Recordset
Sql = "select 数据.学号,数据.姓名,数据.sex,数据.mz,数据.jg,数据.ymd,数据.age,数据.zy,point.xh from 数据,point where 数据.姓名=point.name"
Rs.Open Sql, Conn, 1, 3

End Sub

我看不懂Len(Err

LandMDB()是你自定义的函数,它的返回值是“LandMDB”

在数据库链接成功时,没有返回值,那么“LandMDB(App.Path & "\db1.mdb") ”是空值,这样“ErrInfo ="" ”,那么“Len(ErrInfo)”=0了,就不会发生数据库载入错误了;

相反,如果数据库链接不成功,函数就会产生错误,这时“LandMDB(App.Path & "\db1.mdb")”的返回值是“连接数据库错误,请检查[ App.Path & "\db1.mdb" ]是否存在”,那么“Len(ErrInfo)”<>0了,就会发生数据库载入错误,并且用提示框提示你:错误类型

Public Function LandMDB(ByVal vFile As String) As String
On Error Resume Next
Sql = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & vFile & ";Persist Security Info=False"
Conn.Open Sql
If Err <> 0 Then LandMDB = "连接数据库错误,请检查[ " & vFile & " ]是否存在。"
End Function

如果连接发生错误,返回
"连接数据库错误,请检查[ " & vFile & " ]是否存在。"
正确返回空字符