一、module连接数据库部分是这样写的
Public conn As ADODB.Connection
Public rs As ADODB.Recordset
Public addFlag As Boolean '声明部分
Public Function OpenCn(ByVal Cip As String, ByVal users As String, ByVal pw As String) As Boolean '连接模块 填写数据库等信息
Dim mag As String
On Error GoTo strerrmag
Set conn = New ADODB.Connection
conn.ConnectionTimeout = 25
sql = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;password=;Initial Catalog=MS-20151109NFVH;Data Source=Cip"
conn.ConnectionString = sql
conn.Open
OpenCn = True
If conn.State = 1 Then addFlag = True
Exit Function
strerrmag:
mag = "Data can't connect"
Call MsgBox(mag, vbOKOnly, "Error:Data connect")
addFlag = False
Exit Function '连接错误消息
二、窗体部分是通过3个test传递3个参数,分别是OpenCn函数对应的参数。
最后通过测试按钮测试数据库连接是否成功。窗体代码如下:
Private Sub Command1_Click()
a = Trim(Text1.Text)
b = Trim(Text2.Text)
c = Trim(Text3.Text)
Call OpenCn(a, b, c)
Print conn.State
Print addFlag
If addFlag = True Then MsgBox ("OK")
Call openRs("select * from dressinfo")
Set DataGrid1.DataSource = rs
'rs.Close
End Sub
注意:服务器名称是 Data Source 而不是 Initial Catalog
SQLOLEDB是2000的驱动,2008用下面的。
sql = "Provider=SQLNCLI;Server=MS-20151109NFVH;Database=pubs;Uid=sa;Pwd=;"