ExcelVBA连接Oracle
时间:2021-07-01 10:21:17
帮助过:4人阅读
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文件夹下即可解决。
ExcelVBA连接Oracle
标签: