mrzv Пользователь Сообщений: 44 |
#1 31.08.2018 12:11:55 Здравствуйте, раньше не имел дела с подключением к БД. Прошу помочь.
но как настроить под свой лад не пойму. На счет Data Source=***;Password=***;User ID=*** все понятно |
||
ivanok_v2 Пользователь Сообщений: 712 |
Пример 1
ConnectionString для всех языков програмирования однаковая. |
mrzv Пользователь Сообщений: 44 |
#3 31.08.2018 13:01:35
Как тогда определить какой драйвер мне нужно использовать? |
||
Nordheim Пользователь Сообщений: 3154 |
Я подключаюсь так «Provider=msdaora» «Все гениальное просто, а все простое гениально!!!» |
sokol92 Пользователь Сообщений: 4445 |
#5 31.08.2018 13:14:12
Владимир |
||
mrzv Пользователь Сообщений: 44 |
#6 31.08.2018 13:17:35 Вот такую ошибку мне выдает на строке подключения
Run-time error 3706 Изменено: mrzv — 31.08.2018 13:20:59 |
||
sokol92 Пользователь Сообщений: 4445 |
Установите клиент Oracle в полном объеме. По умолчанию указанный выше драйвер может и не устанавливаться. Кроме того, учтите, что разрядности (32- или 64-) клиента Oracle и MS Office должны совпадать. |
sokol92 Пользователь Сообщений: 4445 |
Проверить доступность провайдера можно через Меню/Данные/Из других источников/Из мастера подключений/Дополнительно (путь дан для Excel 2016). Имя провайдера: Oracle Provider for OLE DB.Там же можно протестировать его работоспособность. Изменено: sokol92 — 31.08.2018 14:22:37 |
mrzv Пользователь Сообщений: 44 |
#9 31.08.2018 15:51:51 Спасибо за совет
Я создал подключение ODBC DNS посмотрел там строку подключения . Вставил её в свой код и все получилось. Только вот русские буквы вопросами…
|
||||
mrzv Пользователь Сообщений: 44 |
#10 31.08.2018 16:21:48 Вот такой код, я получаю нужную мне информацию, но кириллица вопросами. Что я делаю не так?
весь код взял из этой статьи https://www.planetaexcel.ru/forum/index.php?PAGE_NAME=message&FID=1&TID=60251 |
||
sokol92 Пользователь Сообщений: 4445 |
Вы, похоже, подключили провайдер Microsoft, а не Oracle. Мы всегда работали с провайдером Oracle. |
mrzv Пользователь Сообщений: 44 |
#12 03.09.2018 15:29:03 И так с проблемой провайдера я разобрался http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html скачивал вот этот файл:
В этом архиве есть нормальный setup Правильная строка подключения выглядит вот так:
что касается кодировки при использовании DSN вместо Provider, то мне так и не удалось разобраться. Но на мой взгляд способ подключения через Provider более правильный. Спасибо всем за помощь. Изменено: mrzv — 03.09.2018 15:30:00 |
|||||||
sokol92 Пользователь Сообщений: 4445 |
|
bedvit Пользователь Сообщений: 2477 Виталий |
#14 03.09.2018 23:46:15 Владимир, работаем тоже с родными драйверами Oracle. Microsoft не используем. «Бритва Оккама» или «Принцип Калашникова»? |
One rather old application I’ve supported for several years loads data from Excel spreadsheets into a reporting database. These Excel spreadsheets have always been manually updated by several users. However, because the data that the users are entering into these spreadsheets are first being entered into another separate application database, these users have been doing double-entry – a redundant process which can be easily remedied by various means.
Ideally, the solution for this problem would be to extract the data from the application database and load it into the reporting database using an SSIS package. Unfortunately, that would require some redevelopment of the application which loads data into the reporting database, and we (and the customers) have no bandwidth for that. So I came up with a quick workaround that made everyone happy – using a VBA macro to automatically populate the spreadsheets with data when the users open them.
The tricky part here was getting Excel to connect to Oracle with the least amount of work having to be done on the users’ PCs, which are remote from my location.
First of all, since these users don’t require SQL Plus or any development tools for Oracle, the full client software was unnecessary. Also, the Oracle Instant Client could be pushed to the users with Altiris Deployment Solution.
I had the Instant Client software installed on the PCs, then I added the requisite database connection information to the tnsnames.ora file.
Nota bene: In the Instant Client (or at least in our setup, using version 11.2.0.4) the tnsnames file is in
C:oracleinstantclient_11_2_0_4 rather than in C:oracleproduct11.2.0.4client_1NETWORKADMIN as it often would be in the full Oracle client.
The connection in VBA was simple enough, but not immediately obvious – notice that the connection string includes “Microsoft ODBC Driver for Oracle” rather than an Oracle driver; even though this is used, no ODBC connection needs to be set up in the ODBC Data Source Administrator. It is only imperative that the proper entries exist in the tnsnames.ora file, and that the Microsoft ActiveX Data Object Library is installed and referenced in Excel. (Add References by navigating to Tools –> References in the VBA editor in Excel.)
In a subroutine, this code was used to connect to the database and pull data.
Dim SQL_String As String Dim dbConnectStr As String Dim con As New ADODB.Connection Dim recset As New ADODB.Recordset Dim strUid As String Dim strPwd As String Dim strEnv As String Dim strDSN As String Dim iRow As Integer strEnv = "prod" strUid = "username" strPwd = "password" If strEnv = "prod" Then strDSN = "(prod database net_service_name* from tnsnames)" Else strDSN = "(dev database net_service_name* from tnsnames)" End If dbConnectStr = "Driver={Microsoft ODBC for Oracle}; " & _ "Server=" & strDSN & ";" & _ "uid=" & strUid & ";pwd=" & strPwd & ";" con.ConnectionString = dbConnectStr con.Open SQL_String = "(insert SQL query here)" recset.Open SQL_String, con iRow = 0 Do While Not recset.EOF 'Have a loop here to go through all the fields Sheet1.Range("A" & iRow).Value = recset.Fields("colname") ' colname = Column Name from SQL query ' &c. ... iRow = iRow + 1 recset.MoveNext Loop recset.Close con.Close
* net_service_name
Dear Friends,
Using Excel Macros (VBA) you can connect to Databases like SQL, Oracle or Access DB. In this Article, I will teach you, how you can do a connection with a Oracle Server.
We can do connection with Oracle either by giving SID (Oracle System ID) or Service Name. Whichever is available for the connection, we can use them to connect to the Oracle Database.
Prerequisite
Before running the below code, you need to Add reference for ADODB Connection. If you do not know how to add references for ADODB connection in Excel workbook, follow below steps.
Step to Add ADODB Connection References in Excel
1. Go to VB Editor Screen (Alt+F11)
2. Tools –> References…
3. From the List of Available References Select “Microsoft ActiveX Data Objects 2.0 Library” You can select 2.0 Version or any other higher version of this reference.
4. Click OK
Connection String with SID
Connection String with Service(DB Name)
Oracle Connection String with SID:
Use the below Code for connecting to the Oracle Database.
Sub Ora_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
'---- Replace below highlighted names with the corresponding values
strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=Your Host Name)(PORT=Port Number))" & _
"(CONNECT_DATA=(SID=SID of your Database))); uid=User ID; pwd=Password;"
'--- Open the above connection string.
con.Open (strCon)
'--- Now connection is open and you can use queries to execute them.
'--- It will be open till you close the connection
End Sub
Oracle Connection String with Service:
Use the below Code for connecting to the Oracle Database.
Sub Ora_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
'--- Replace below highlighted names with the corresponding values
strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=Your Host Name)(PORT=Enter Port Number))" & _
"(CONNECT_DATA=(SERVICE_NAME=database))); uid=Enter User ID; pwd=Enter Password;"
'--- Open the above connection string.
con.Open (strCon)
'--- Now connection is open and you can use queries to execute them.
'--- It will be open till you close the connection
End Sub
Read this Also:
- How to Connect to SQL Database using Excel Macros
- How to Connect to Oracle Database using Excel Macros
- How to Connect to Access Database using Excel Macros
- Remove From My Forums
-
Question
-
I want to import data into MS excel 2010 from SQL developer (Oracle) using VBA macro
I am using below code but not able to connect to SQL devevloper.
Kindly help.
Sub ImportData() Sheets("sheet1").Select With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _ "OLEDB;Provider=MSDAORA.1;User ID=MY_USER;password= MY_PW;Data Source=sourceName", Destination _ :=Range("$A$1")).QueryTable .CommandType = xlCmdSql .CommandText = "Select Main.[ID],Main.[Count1] From Main Where Main.[Count1] > 25" .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .PreserveColumnInfo = True .Refresh BackgroundQuery:=False End With End Sub
Answers
-
-
Proposed as answer by
Thursday, February 18, 2016 9:23 AM
-
Marked as answer by
Edward8520Microsoft contingent staff
Tuesday, February 23, 2016 7:10 AM
-
Proposed as answer by