我想从excel宏连接到DB2 ...这是我的代码,但它不起作用,它给出的错误是'运行时错误'...任何人都可以帮助我......
Option Explicit
Dim DBCONSRT, QRYSTR As String
Dim DBCON, DBRS As Object
Private Sub query()
DBCONSRT = "Driver=jdbc:db2://my_host;Database=PRTHD;hostname=NZ1;port=5355;protocol=TCPIP; uid=my_user;pwd=my_pass"
'CHANGE THE BELOW QUERY STRING ACCORDING TO YOUR NEED
QRYSTR = "select * from PRTHD.STRSK_OH_EOO"
Set DBCON = CreateObject("ADODB.Connection")
DBCON.ConnectionString = DBCONSRT
DBCON.Open
'BELOW CODE USED TO GET THE DATABASE CONECTION AND EXECUTE THE QUERY CHANGE ACCORDIGN TO YOUR NEED
Set DBRS = CreateObject("ADODB.Recordset")
With DBRS
.Source = QRYSTR
Set .ActiveConnection = DBCON
.Open
End With
End Sub
编辑:我已将代码更改为以下内容,但我仍然收到错误消息。错误是“无法创建对象”..可以帮助我..
Dim DBCONSRT, QRYSTR As String
Dim DBCON As Object
Sub query()
DBCONSRT = "Provider=MSDASQL.1;Persist Security Info=False;User ID=user;Data Source=NZ1;DSN=NZ1;UID=user;SDSN=;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=PRTHD;"
DBCON = CreateObject("OLEDB.Connection")
DBCON.ConnectionString = DBCONSRT
DBCON.Open()
End Sub
答案 0 :(得分:0)
我非常确定JDBC功能不受vba支持,如果您尝试将其集成到Excel中,我认为您需要使用ODBC连接器连接到DB2。
Private Sub query()
DBCONSRT = "Provider=MSDASQL.1;Persist Security Info=False;User ID=user;Data Source=NZ1;DSN=NZ1;UID=user;SDSN=;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=PRTHD;"
Using connection = New OleDbConnection(DBCONSRT )
connection.Open()
Dim cmd = connection.CreateCommand()
cmd.CommandText = QRYSTR //This is where your sql statement should go, or the variable that is equal to the query.
Using dr = cmd.ExecuteReader()
//Process your query results here
End Using
End Using
End Sub
答案 1 :(得分:0)
从更改
开始DBCON = CreateObject("OLEDB.Connection")
到
Set DBCON = CreateObject("ADODB.Connection")
如果您仍然收到错误double-check your connection string。