1、在连接数据库前首先要在VB菜单中“工程”-“引用”从中选择 microsoft activeX Data objects 2.6 library和 microsoft activeX Data objects recordset 2.6两个组件,这是在连接数据前所必做的工作。
2、接下来定义ADO的连接对象,如下所示:
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
第一种方法采用的是无源的数据库连接方法
conn.ConnectionString = "Driver={sql server}server=JSZX3-11uid=sapwd=database=wzc"
conn.ConnectionTimeout = 30
conn.Open
rs.Open "select 用户名,密码 from login where 用户名='" &Trim(Combo1.Text) &"' And 密码='" &Trim(Text1.Text) &"'", conn, adOpenStatic, adLockReadOnly, adCmdText
If rs.EOF = True And rs.BOF Then
m = MsgBox("请重新登录", vbExclamation)
Text1.Text = ""
Text1.SetFocus
Else
Form1.Hide
End If
rs.Close
这是第二种方法连接数据库的方法,这一种方法是采用有源的方法与数据库连接的方法,代码如下所示:
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.ConnectionString = "DSN=loginuid=sapwd="
conn.ConnectionTimeout = 30
conn.Open
rs.Open "select 用户名 from login", conn, adOpenStatic, adLockReadOnly, adCmdText
Dim i As String
For t = 0 To Val(rs.RecordCount) - 1
i = Trim(rs.Fields("用户名").Value)
rs.MoveNext
Combo1.AddItem i
Next t
rs.Close
dimdbConn
As
ADODB.Connection
'定义一个ADODB连接
dim
MenuRs
As
ADODB.Recordset
'定义Recordset对象
dim
WordRs
As
ADODB.Recordset
Function
Conn2DB(byval
dbname
as
string)
As
Boolean
'数据库连函数,dbname为数据库文件的绝对路径
Dim
connStr
As
String
'
Access连接字符串
conStr
=
"Provider=Microsoft.Jet.OLEDB.4.0Data
Source="
&
dbName
&
"Persist
Security
Info=FalseJet
OLEDB:Database
Password=abcdef"
Set
dbConn
=
New
ADODB.Connection
'定义一个ADODB连接对象
If
dbConn.State
<>
adStateOpen
Then
'判断ADODB连接是否打开
dbConn.Open
conStr
'如果不是打开状态
就打开连接
End
If
Conn2DB
=
True
End
Function
Function
CloseDb()
As
Boolean
If
dbConn.State
=
adStateOpen
Then
dbConn.Close:
Set
dbConn
=
Nothing
End
If
End
Function
Private
Sub
Form_Load()
dim
dbname
as
string
dbname="D:\db.mdb"
‘数据库文件路径
if
Conn2DB(dbname)=true
then
msgbox
"连接数据库成功!"
CloseDb
end
if
End
sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)