VB怎么通过INI文件连接SQL数据库啊?要怎么样写代码和写ini文件啊?
我想写一个ini的文件 VB通过调用ini文件连接SQL数据库 该怎么写啊?
LZ意思是不是说要将连接SQL数据库字符串写入INI文件,以便随时可以更改。
下面代码供你参考:
'连接SQL服务器---此段代码不用写入SQL文件
Public Function sqlConnect(ByVal cnThis As ADODB.Connection, ByVal strServer As String, ByVal strUser As String, ByVal strPass As String, Optional ByVal strDataBase As String = "")
Dim strSQL As String
'生成连接字符串
strSQL = "provider=sqloledb;server=" & strServer & ";user id=" & strUser & ";password=" & strPass
If strDataBase <> "" Then strSQL = strSQL & ";database=" & strDataBase '如果需要连接到数据库
cnThis.Open strSQL
End Function
'读取SQL服务器配置信息
Public Sub readServer()
On Error GoTo aaaa
Dim strTmp As String, strT() As String
Open GetApp & "sql.ini" For Input As #1
If EOF(1) = False Then Line Input #1, strTmp
Close #1
strTmp = Trim(strTmp)
If strTmp <> "" Then
strT = Split(strTmp, "||")
For i = 0 To 3
strT(i) = strT(i)
Next
strSQLServer = strT(0)
strSQLUser = strT(1)
strSQLPW = strT(2)
strSQLDB = strT(3)
End If
Exit Sub
aaaa:
strSQLServer = ""
strSQLUser = ""
strSQLPW = ""
strSQLDB = ""
End Sub
'保存SQL服务器配置信息
Public Sub SaveServer(ByVal strServer As String, ByVal strUser As String, ByVal strPass As String, ByVal strDataBase)
On Error GoTo aaaa
Open GetApp & "sql.ini" For Output As #1
Print #1, strServer & "||" & strUser & "||" & strPass & "||" & strDataBase
Close #1
Exit Sub
aaaa:
MsgBox "保存 SQL 服务器信息失败!", vbCritical
End Sub
下面代码供你参考:
'连接SQL服务器---此段代码不用写入SQL文件
Public Function sqlConnect(ByVal cnThis As ADODB.Connection, ByVal strServer As String, ByVal strUser As String, ByVal strPass As String, Optional ByVal strDataBase As String = "")
Dim strSQL As String
'生成连接字符串
strSQL = "provider=sqloledb;server=" & strServer & ";user id=" & strUser & ";password=" & strPass
If strDataBase <> "" Then strSQL = strSQL & ";database=" & strDataBase '如果需要连接到数据库
cnThis.Open strSQL
End Function
'读取SQL服务器配置信息
Public Sub readServer()
On Error GoTo aaaa
Dim strTmp As String, strT() As String
Open GetApp & "sql.ini" For Input As #1
If EOF(1) = False Then Line Input #1, strTmp
Close #1
strTmp = Trim(strTmp)
If strTmp <> "" Then
strT = Split(strTmp, "||")
For i = 0 To 3
strT(i) = strT(i)
Next
strSQLServer = strT(0)
strSQLUser = strT(1)
strSQLPW = strT(2)
strSQLDB = strT(3)
End If
Exit Sub
aaaa:
strSQLServer = ""
strSQLUser = ""
strSQLPW = ""
strSQLDB = ""
End Sub
'保存SQL服务器配置信息
Public Sub SaveServer(ByVal strServer As String, ByVal strUser As String, ByVal strPass As String, ByVal strDataBase)
On Error GoTo aaaa
Open GetApp & "sql.ini" For Output As #1
Print #1, strServer & "||" & strUser & "||" & strPass & "||" & strDataBase
Close #1
Exit Sub
aaaa:
MsgBox "保存 SQL 服务器信息失败!", vbCritical
End Sub
温馨提示:答案为网友推荐,仅供参考
第1个回答 2010-01-16
有必要通过INI文件么,INI文件被用来对操作系统或特定程序初始化或进行参数设置。VB读写INI文件可以用API函数,也可以直接用读写文本文档的方式,简单点可以将ADO控件连接SQL的一些参数用写文本文档的方式写入一个后缀为ini的文件里面,然后用一般的读取方法读出来给ADO控件赋值实现连接数据库。本回答被网友采纳