谢谢楼上的回复,可能我在上面说得不是很清楚,下面我把在窗体中能实现的代码帖上来,但现在我是想在模块中实现同样的功能,初始化数据库连接。
Private Declare Function GetPrivateProfileString Lib "kernel32" _
Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, _
ByVal lpKeyName As Any, ByVal lpDefault As String, _
ByVal lpReturnedString As String, ByVal nSize As Long, _
ByVal lpFileName As String) As Long
Private Declare Function WritePrivateProfileString Lib "kernel32" _
Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, _
ByVal lpKeyName As Any, ByVal lpString As Any, _
ByVal lpFileName As String) As Long
Public Conn As New ADODB.Connection
Private Sub Cmd_OK_Click()
Dim success As Long
success = WritePrivateProfileString("Student", "ServerName", txtServerName.Text, App.Path + "\Account.ini")
'参数一、 Section Name 参数二、於.ini中的项目 参数三、项目的内容 参数四 .ini文件的名称
success = WritePrivateProfileString("Student", "DataBase", txtDataBase.Text, App.Path + "\Account.ini")
success = WritePrivateProfileString("Student", "DBLogon", txtDBLogon.Text, App.Path + "\Account.ini")
success = WritePrivateProfileString("Student", "LogonPass", txtLogonPass.Text, App.Path + "\Account.ini")
End Sub
Private Sub Cmd_Cancel_Click()
Call form_load
End Sub
Private Sub Cmd_Exit_Click()
End
End Sub
Private Sub Cmd_Test_Click()
On Error GoTo ErrorDB
Dim strConn As String
Set Conn = New ADODB.Connection
strConn = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=" + txtDBLogon.Text + ";Password=" + txtLogonPass.Text + ";Initial Catalog=" + txtDataBase.Text + ";Data Source=" + txtServerName.Text + ";"
Conn.Open strConn
If Conn.State <> adStateOpen Then
MsgBox "数据库连接失败"
End
Else
MsgBox "数据库连接成功", vbOKOnly, "提示"
End If
Conn.Close
Set Conn = Nothing
Exit Sub
ErrorDB:
If Conn.State = adStateOpen Then Conn.Close
If Not IsNull(Conn) Then Set Conn = Nothing
MsgBox "数据库连接失败", vbOKOnly, "提示"
End Sub
Private Sub form_load()
Dim ret As Long
Dim buff As String
buff = String(255, 0)
ret = GetPrivateProfileString("Student", "ServerName", ".", buff, 256, App.Path + "\Account.ini")
'若.ini Student中无ServerName,则采用参数三的值
txtServerName.Text = buff
buff = String(255, 0)
ret = GetPrivateProfileString("Student", "DataBase", "Student", buff, 256, App.Path + "\Account.ini")
txtDataBase.Text = buff
buff = String(255, 0)
ret = GetPrivateProfileString("Student", "DBLogon", "Sa", buff, 256, App.Path + "\Account.ini")
txtDBLogon.Text = buff
buff = String(255, 0)
ret = GetPrivateProfileString("Student", "LogonPass", " ", buff, 256, App.Path + "\Account.ini")
txtLogonPass.Text = buff
End Sub
Account.ini文件内容
[Student]
ServerName=192.168.0.1
DataBase=Student
DBLogon=Sa
LogonPass=Sa
[此贴子已经被作者于2006-9-12 15:33:41编辑过]