标签:
VBA连接Oracle需要添加引用:
之后,连接字符串为:Provider = MSDAORA.1;Password=******;User ID=XXXXXXX;Data Source=DBID;Persist Security Info=True
然后使用ado的标准封装使用即可,1、使用ADO.CONNECTION,打开连接,2、使用ADO.RECODESET查询DB,使用connection.Excute执行更新删除等操作。
具体代码如下:
Public Sub ConOra()Dim sht As Worksheet Set sht = ActiveSheet On Error GoTo ErrMsg: ‘连接串 Dim ConnDB As ADODB.Connection Set ConnDB = New ADODB.Connection Dim ConnStr As String ‘ 结果集 Dim DBRst As ADODB.Recordset Set DBRst = New ADODB.Recordset ‘SQL文 Dim SQLRst As String Dim OraOpen As Boolean OraOpen = False ‘Oracle数据库的相关配置 ConnStr = getConnStr() ‘ ConnDB.CursorLocation = adUseServer ConnDB.Open ConnStr ConnDB.Execute ("select * from dual") OraOpen = True ‘成功执行后,数据库即被打开 ‘MsgBox "Connect to the oracle database Successful!", vbInformation, "Connect Successful" ‘DBRst.ActiveConnection = ConnDB ‘DBRst.CursorLocation = adUseServer ‘DBRst.LockType = adLockBatchOptimistic SQLRst = "Select * From " & getTableName() & " where rownum = 1 " ‘DBRst.Open SQLRst, ConnDB, adOpenStatic, adLockBatchOptimistic DBRst.Open SQLRst, ConnDB
查询之后,对于RecordSet 的使用:
1、获取列名:
For i = 1 To DBRst.Fields.Count sht.Cells(2, i) = DBRst.Fields(i - 1).Name Next
2、获取值:
Do Until DBRst.EOF For i = 1 To DBRst.Fields.Count sht.Cells(4, i) = DBRst.Fields(i - 1).Value Next i DBRst.MoveNext Loop
3、判断RecordSet是否为空:
If DBRst.BOF And DBRst.EOF Then MsgBox "数据库中未查询出任何数据,请将做成的数据写入第4行!", vbInformation, "提示" End If
4、记得关闭连接哟。
5、如果按照以上方法,仍无无法连接DB,并提示:连接无法打开,这是因为Office的安装目录中包含(86)导致的,重新按照OFFICE到其他非program文件夹下即可解决。
标签:
原文地址:http://www.cnblogs.com/IDECIDETODOIT/p/4607798.html