Oracle odbc driver configuration настройка
Этот пример показывает, как настроить источник данных и подключение к базе данных Oracle ® с помощью приложения Database Explorer или командной строки. Этот пример использует драйвер OraClient11g_home1 ODBC, чтобы соединиться с базой данных Oracle 11g Enterprise Edition.
Шаг 1. Проверьте установку драйвера.
Драйвер ODBC обычно предварительно устанавливается на вашем компьютере. Для получения дополнительной информации об установке драйвера или поиске и устранении неисправностей установки, свяжитесь со своим администратором базы данных или обратитесь к вашей документации базы данных относительно драйверов ODBC. Для получения информации о Microsoft ® ODBC Data Source Administrator смотрите Установку драйвера.
Примечание:
Шаг 2. Настройте источник данных с помощью приложения Database Explorer.
Приложение Database Explorer получает доступ к Microsoft ODBC Data Source Administrator автоматически, когда вы конфигурируете источник данных ODBC. Также можно получить доступ к Microsoft ODBC Data Source Administrator с помощью функции configureODBCDataSource .
Откройте приложение Database Explorer путем нажатия на вкладку Apps на MATLAB ® Toolstrip. Затем справа от раздела Apps кликните по стрелке Show more, чтобы открыть галерею приложений. Под Database Connectivity and Reporting нажмите Database Explorer. Также введите databaseExplorer в командной строке.
В разделе Data Source выберите Configure Data Source> Configure ODBC data source.
В диалоговом окне ODBC Data Source Administrator вы задаете источник данных ODBC.
Совет
При подготовке источника данных ODBC можно задать пользовательское имя источника данных (DSN) или систему DSN. Пользователь DSN характерен для человека, регистрируемого в машину. Только этот человек видит источники данных, которые заданы на пользовательской вкладке DSN. Система DSN не характерна для человека, регистрируемого в машину. Любой человек, который регистрирует в машину, видит источники данных, которые заданы на системной вкладке DSN. Ваша способность настроить пользователя DSN или система, DSN зависит от базы данных и драйвера ODBC, который вы используете. Для получения дополнительной информации свяжитесь с администратором базы данных или обратитесь к документации драйвера ODBC.
Кликните по вкладке System DSN, и затем нажмите Add.
Диалоговое окно Create New Data Source открывает и отображается список установленных драйверов ODBC.
Выберите драйвер ODBC Oracle in OraClient11g_home1 .
Примечание
Имя драйвера ODBC может отличаться.
Нажмите Finish.
В диалоговом окне Oracle ODBC Driver Configuration введите соответствующее имя для источника данных. Вы используете это имя, чтобы установить связь с вашей базой данных. Здесь, в поле Data Source Name, введите ORA как имя источника данных. В поле Description введите описание для этого источника данных, такого как Oracle database . В поле TNS Service Name введите имя своей базы данных.
Можно настроить источник данных ODBC с или без аутентификации Windows.
Чтобы установить источник данных без аутентификации Windows, введите свое имя пользователя в поле User ID. Или, чтобы установить источник данных с аутентификацией Windows, оставьте это незаполненное поле. Оставьте Application, Oracle, Workarounds и вкладки SQLServer Migration с настройками по умолчанию.
Нажмите Test Connection, чтобы протестировать связь с вашей базой данных. Диалоговое окно Driver Connect ODBC Oracle открывается. Если вы устанавливаете источник данных с аутентификацией Windows, диалоговое окно Testing Connection открывается.
Нажмите OK в диалоговом окне Oracle ODBC Driver Configuration. Диалоговое окно ODBC Data Source Administrator показывает источнику данных ODBC ORA .
После того, как вы завершаете настройку источника данных, соединяетесь с базой данных Oracle с помощью приложения Database Explorer или командной строки с нативной связью ODBC.
Шаг 3. Подключение с помощью приложения Database Explorer или командной строки.
Соединитесь с Oracle Используя приложение Database Explorer
На вкладке Database Explorer, в разделе Data Source, нажимают New Query.
В Подключении к диалоговому окну Data Source соединитесь с аутентификацией Windows путем выбора источника данных, который вы задали из списка Data Source. Оставьте пробел полей Username и Password. Нажмите Connect.
Или, соединитесь без аутентификации Windows путем выбора источника данных, который вы задали. Введите имя пользователя и пароль. Нажмите Connect.
Диалоговое окно Catalog и Schema открывается.
В списке Schema выберите схему. Нажмите OK.
Приложение Database Explorer соединяется с базой данных и таблицами базы данных отображений в панели Data Browser. Вкладка источника данных появляется справа от панели. Заголовок вкладки источника данных является именем источника данных, которое вы задали во время настройки. Вкладка источника данных содержит пустой SQL Query и панели Data Preview.
Выберите таблицы в панели Data Browser, чтобы запросить базу данных.
Закройте вкладку источника данных, чтобы закрыть SQL-запрос и соединение с базой данных.
Совет
Чтобы закрыть соединение с базой данных, закройте все вкладки, которые имеют заголовки, начинающиеся с имени соответствующего источника данных. Например, если именем источника данных является ORA , и две вкладки под названием ORA и ORA1 открыты, то закрывают обе вкладки.
Чтобы закрыть все соединения с базой данных, закройте приложение Database Explorer.
Соединитесь с Oracle Используя драйвер ODBC и командную строку
Чтобы соединиться с аутентификацией Windows, соединитесь с базой данных с аутентифицируемым именем источника данных ODBC и пустым именем пользователя и паролем. Например, этот код принимает, что вы соединяетесь с источником данных под названием Oracle_Auth .
Или, чтобы соединиться без аутентификации Windows, соединитесь с базой данных с именем источника данных ODBC. Например, этот код принимает, что вы соединяете с источником данных под названием Oracle с именем пользователя username и пароль pwd .
When working with databases on RStudio Desktop Pro and other RStudio professional products, it is strongly recommended to use the RStudio Professional Drivers. Not only these come with full support, but also they simplify the installation and configuration process is most cases, not requiring many of the steps detailed below.
Diagram of Using RStudio’s Professional Drivers
Using other drivers
For Linux and MacOS, ODBC drivers should be compiled against unixODBC. Drivers compiled against iODBC may also work, but are not fully supported.
After installation of the driver manager and driver, you will have to register the driver in a odbcinst.ini file for it to appear in odbc::odbcListDrivers() .
Microsoft Windows
Database Drivers
Windows is bundled with ODBC libraries; however, drivers for each database need to be installed separately. Windows ODBC drivers typically include an installer that must be run to install the drivers in the proper locations.
Administration
The ODBC Data Source Administrator application is used to manage ODBC data sources on Windows.
Apple MacOS
Installation
Install homebrew to install database drivers easily on MacOS
Install UnixODBC, which is required for all databases
Setting up database connections
See the section with the same name in the Linux section.
Linux Debian / Ubuntu
Installation
The apt-get command can be used to install database drivers easily on Linux distributions that support it, such as Debian and Ubuntu.
- Install UnixODBC, which is required for all databases
- Install common DB drivers (optional)
Setting up database connections
On MacOS and Linux, there are two separate text files that need to be edited. UnixODBC includes a command-line executable called odbcinst , which can be used to query and modify the DSN files. However, these are plain text files you can also edit by hand if desired.
There are two different files used to set up the DSN information:
odbcinst.ini defines driver options
odbc.ini defines connection options
odbcinst.ini
This file contains the driver information, particularly the name of the driver library. Multiple drivers can be specified in the same file.
odbc.ini
This file contains the connection information, particularly the username, password, database and host information. The Driver line corresponds to the driver defined in odbcinst.ini .
See also: unixODBC without the GUI for more information and examples.
Location
The DSN configuration files can be defined globally for all users of the system, often at /etc/odbc.ini or /opt/local/etc/odbc.ini . The file location depends on what option was used when compiling unixODBC; odbcinst -j can be used to find the exact location. Alternatively, the ODBCSYSINI environment variable can be used to specify the location of the configuration files. Ex. ODBCSYSINI=~/ODBC
A local DSN file can also be used with the files ~/.odbc.ini and ~/.odbcinst.ini .
Connecting to a Database in R
Databases can be connected by specifying a connection string directly, or with DSN configuration files.
Connection Strings
Pass the connection parameters as arguments to the dbConnect() function.
For database-specific settings, go to the Databases section in the menu and look for the page that matches the desired database type.
DSN Configuration files
ODBC configuration files are another option to specify connection parameters; they allow you to use a Data Source Name (DSN) to make it easier to connect to a database.
For more information about how DSN can be used, check out the following articles in this site:
Setting up an Oracle ODBC Driver and Data Source requires more steps than the Microsoft SQL Server database setup. This article explains the steps including tnsnames.ora configuration.
Connecting to an Oracle database via and ODBC driver requires the following steps:
- Install the ODAC (Oracle Data Access Components) or Oracle Client on the Workstation or Application Server.
- Setup the SQLNET and TNSNAMES files in the Client or ODAC home’s Admin directory.
- Use the ODBC Data Source configuration tools to create the ODBC Data Source.
The following blog shows the process involved for each of these steps to get you a working connection to an Oracle database.
Prerequisites: Java JRE or SDK 6 Update 27 or later. These are required by the Oracle Universal Installer to run the ODAC installation program.
Step 1 – Install the ODAC or Oracle Client
In this example we will be installing the ODAC client to complete an ODBC setup on a Windows 7 (64-bit) operating system. You can install the full administrative option of the Oracle Client to obtain the ODBC driver.
Download the ODAC112030_x64.zip file from Oracle’s web site:
Unzip the file to a location of your choosing.
Locate the Setup.exe file under the root directory of the extracted zip file’s directories.
Double-click to run the setup program.
In the ‘Oracle Universal Installer’, click the Next button.
In the ‘Select a Product to Install’ dialog, go with the default ‘Oracle Data Access Components for Oracle Client 11.2.0.3.0’ option.
In the ‘Install Location’ dialog, enter a path to install the ODAC home directory to in the ‘Oracle Base:’ field.
In the ‘Available Product Components’ dialog, go with the default options.
In the ‘Summary’ dialog, verify that the components you have selected for install include the ‘Oracle ODBC Driver for Instant Client 11.2.0.3.0’.
When the installation is complete, click ‘Exit’.
This concludes the steps for installing the ODBC drivers.
Step 2 – Setup the SQLNET and TNSNAMES files
Locate the SQLNET.ora and TNSNAMES.ora in the ‘samples’ directory of the newly installed Oracle client home directory. This is typically:
Where ‘johndoe’ is the windows user name.
Copy these two files into the ‘Admin’ directory above.
Open the ‘TNSNAMES.ora’ file in Notepad and enter your Oracle database details in the file.
Save your changes.
Note: the ‘SQLNET.ora’ generally doesn’t need to be changed.
Step 3 – Create the ODBC Data Source
In the Windows Start menu, click on the Data Sources (ODBC) icon that was created by the ODAC client install.
In the ‘User DSN’ tab of the ‘ODBC Data Source Administrator’ dialog, click Add.
In the ‘Create New Data Source’ dialog, select the ‘Oracle in OraClient 11g_home1’ driver.
In the ‘Oracle ODBC Driver Configuration’ dialog, enter the details of your data source.
Note: you should be able to select the TNS Service Name from the drop down list. This name will be that which you named in the TNSNAMES.ora file’s Alias = section.
This article explains the process to configure the ODBC driver for oracle 19c. I am covering the following topics:
- How to configure the ODBC driver using ODBC Data Source Administrator
- Create a sample PowerBI report to populate and view the data from the oracle database
Environment setup
I have installed oracle 19c on my workstation. When we install the oracle database on the workstation and the oracle database, the setup installs the client connectivity tools and drivers. I have created a database named ELTECH. It is a sample database, and it contains the oracle sample schemas. I have enabled the HR schema of the ELTECH database. The HR schema is associated with the HR user, so we will enable the HR user by running the following query.
SQL> Alter User HR account unlock;
User altered.
Once the schema is enabled, I have changed the password of the HR user.
SQL> Alter user HR identified by tiger;
User altered.
To view the data populated from the oracle database, I have installed the PowerBI for Desktop on my workstation. First, let us configure the ODBC driver.
Configure ODBC Driver
The DSN is used in any application that uses the ODBC driver to connect to the database. We will create a DSN to access the oracle database using ODBC Driver. We can create a DSN by using the ODBC Data Source Administrator.
The ODBC Data Source administrator MMC (Microsoft management console) is in the Administrative tools directory of the control panel. Open Control Panel 🡪 Administrative tools 🡪 ODBC Data Source Administrator (64-bit) 🡪 Select System DSN 🡪 Click on the Add button on the ODBC Data Source Administrator dialog box.
Select Oracle in OraDB19Home1 from the list of data sources listed in Create New Data Source dialog box. Click on Finish.
A dialog box named Oracle ODBC Driver Configuration opens. You can specify the following options in the dialog box.
Data Source Name:
Specify the data source name. The DSN will be used to identify the data source uniquely
Description:
Specify the appropriate description of the data source
TNS Service name:
Specify the location of the oracle database from which the ODBC will populate the data. We can get the TNS Service name from the Oracle Net Configuration Assistant. Alternatively, you can find it by executing the following query:
SQL> show parameter service_name
In our case, the TNS Service name will be ELTECH, so specify it in the TNS Service name drop-down box
UserID:
Specify the User ID that you want to use to connect to the oracle database. In this demo, we are using HR users, so specify it in the UserID textbox
The configuration looks like the following screenshot.
Click OK to save the DSN configuration and close the dialog box. The new DSN is visible in ODBC Data Source Administrator.
Now, let us create a sample report using Power BI.
Create a sample report in Power BI
Launch PowerBI Desktop. Click on get data from another source on Add data to your report page.
A dialog box Get Data opens. You can view the various data sources in the dialog box.
Search ODBC from the list select Connect.
Another dialog box From ODBC opens. You can select the desired data source from the Data source name (DSN) drop-down box. We have configured DSN named HRReports, so select it from the list and click OK.
In the Navigator, you can view the list of the tables and objects created in the ELTECH database under HRReports DSN. We want to create a report using the Employees table, so expand HR and select Employees.
The preview of the Employees table is in the right pan. Click on Load to load the data in the report. Once data is loaded in the report, you can view the Employees table in the fields pan. Expand EMPLOYEES to view the list of the columns.
We are going to prepare the report with the following columns:
- First_name
- Last_name
- Job_id
- Phone_number
- Hire_Date
- Salary
When you select the fields, the columns will be added to the report canvas.
As you can see, the data from the employees’ table has been added to the report canvas of PowerBI.
- Note: You can sort the data according to the requirement. You can read Getting started with formatting report visualizations – Power BI to understand how to format the report in Power BI for desktop
Publish the report
Now, let us publish the report. Click on the Publish button on the menu bar of the Power BI desktop. We have not configured the Power BI services so the reports will be published locally.
The Power BI report starts publishing. You can view the following dialog box.
Once the report is published successfully, you can view the following dialog box.
You can view the report in the Power BI workspace. It looks like the following:
Summary
In this article, we learned how we could configure the data source name for the oracle database. This article gives a basic idea of creating a DSN using ODBC Driver of the oracle 19c. I have also explained how we can utilize the ODBC driver to display the Power BI report.
Nisarg Upadhyay is a SQL Server Database Administrator and Microsoft certified professional who has more than 8 years of experience with SQL Server administration and 2 years with Oracle 10g database administration.
- Learn PostgreSQL: Managing PostgreSQL databases - May 5, 2022
- CREATE TABLE statement in SQL Server - April 29, 2022
- Drop temp tables in PostgreSQL - March 22, 2022
Related posts:
About Nisarg Upadhyay
Этот пример показывает, как настроить источник данных и подключение к Oracle ® база данных с помощью приложения Database Explorer или командной строки. Этот пример использует драйвер OraClient11g_home1 ODBC, чтобы соединиться с базой данных Oracle 11g Enterprise Edition.
Шаг 1. Проверьте установку драйвера.
Драйвер ODBC обычно предварительно устанавливается на вашем компьютере. Для получения дополнительной информации об установке драйвера или поиске и устранении неисправностей установки, свяжитесь со своим администратором базы данных или обратитесь к вашей документации базы данных относительно драйверов ODBC. Для получения информации о Microsoft ® ODBC Data Source Administrator, смотрите Установку драйвера.
Примечание:
Database Toolbox™ больше не поддерживает соединение с базой данных с помощью 32-битного драйвера. Используйте 64-битную версию Oracle. Если у вас есть проблемы, работающие с драйвером ODBC, используйте драйвер JDBC вместо этого. Для получения дополнительной информации смотрите Oracle JDBC для Windows. Для получения дополнительной информации о работе с 64-битной версией Windows ® , смотрите Используя Предыдущие Релизы MATLAB.
Шаг 2. Настройте источник данных с помощью приложения Database Explorer.
Приложение Database Explorer получает доступ к Microsoft ODBC Data Source Administrator автоматически, когда вы конфигурируете источник данных ODBC. В качестве альтернативы можно получить доступ к Microsoft ODBC Data Source Administrator с помощью configureODBCDataSource функция.
Откройте приложение Database Explorer путем нажатия на вкладку Apps на MATLAB ® Панель инструментов. Затем справа от раздела Apps кликните по стреле Show more, чтобы открыть галерею Apps. Под Database Connectivity and Reporting нажмите Database Explorer. В качестве альтернативы введите databaseExplorer в командной строке.
В разделе Data Source выберите Configure Data Source> Configure ODBC data source.
В диалоговом окне ODBC Data Source Administrator вы задаете источник данных ODBC.
Совет
При подготовке источника данных ODBC можно задать пользовательское имя источника данных (DSN) или систему DSN. Пользователь DSN характерен для человека, регистрируемого в машину. Только этот человек видит источники данных, которые заданы на пользовательской вкладке DSN. Система DSN не характерна для человека, регистрируемого в машину. Любой человек, который регистрирует в машину, видит источники данных, которые заданы на системной вкладке DSN. Ваша способность настроить пользователя DSN или система, DSN зависит от базы данных и драйвера ODBC, который вы используете. Для получения дополнительной информации свяжитесь с администратором базы данных или обратитесь к документации драйвера ODBC.
Кликните по вкладке System DSN, и затем нажмите Add.
Диалоговое окно Create New Data Source открывает и отображается список установленных драйверов ODBC.
Выберите драйвер ODBC Oracle in OraClient11g_home1 .
Примечание
Имя драйвера ODBC может варьироваться.
Нажмите Finish.
В диалоговом окне Oracle ODBC Driver Configuration введите соответствующее имя для источника данных. Вы используете это имя, чтобы установить связь с вашей базой данных. Здесь, в поле Data Source Name, введите ORA как имя источника данных. В поле Description введите описание для этого источника данных, такого как Oracle database . В поле TNS Service Name введите имя своей базы данных.
Можно настроить источник данных ODBC с или без аутентификации Windows.
Чтобы установить источник данных без аутентификации Windows, введите свое имя пользователя в поле User ID. Или, чтобы установить источник данных с аутентификацией Windows, оставьте это незаполненное поле. Оставьте Application, Oracle, Workarounds и вкладки SQLServer Migration с настройками по умолчанию.
Нажмите Test Connection, чтобы протестировать связь с вашей базой данных. Диалоговое окно Driver Connect ODBC Oracle открывается. Если вы устанавливаете источник данных с аутентификацией Windows, диалоговое окно Testing Connection открывается.
Нажмите OK в диалоговом окне Oracle ODBC Driver Configuration. Диалоговое окно ODBC Data Source Administrator показывает источнику данных ODBC ORA .
После того, как вы завершаете настройку источника данных, соединяетесь с базой данных Oracle с помощью приложения Database Explorer или командной строки с нативной связью ODBC.
Шаг 3. Подключение с помощью приложения Database Explorer или командной строки.
Соединитесь с Oracle Используя приложение Database Explorer
На вкладке Database Explorer, в разделе Connections, нажимают Connect и выбирают источник данных для связи.
Если вы создаете связь с аутентификацией Windows, оставляете пробел полей Username и Password в диалоговом окне связи и нажимаете Connect. В противном случае введите имя пользователя и пароль и нажмите Connect.
Диалоговое окно Catalog и Schema открывается.
В списке Schema выберите схему. Нажмите OK.
Приложение соединяет с базой данных и отображениями свои таблицы в панели Data Browser. Вкладка источника данных появляется справа от панели. Заголовок вкладки источника данных является именем источника данных, которое вы задали во время настройки. Вкладка источника данных содержит пустой SQL Query и панели Data Preview.
Выберите таблицы в панели Data Browser, чтобы запросить базу данных.
Закройте вкладку источника данных, чтобы закрыть SQL-запрос. В разделе Connections закройте соединение с базой данных путем нажатия на Close Connection.
Примечание
Если многочисленные связи открыты, закрывают соединение с базой данных по вашему выбору путем выбора соответствующего источника данных из списка Close Connection.
Соединитесь с Oracle Используя драйвер ODBC и командную строку
Чтобы соединиться с аутентификацией Windows, соединитесь с базой данных с аутентифицируемым именем источника данных ODBC и пустым именем пользователя и паролем. Например, этот код принимает, что вы соединяетесь с источником данных под названием Oracle_Auth .
Или, чтобы соединиться без аутентификации Windows, соединитесь с базой данных с именем источника данных ODBC. Например, этот код принимает, что вы соединяетесь с источником данных под названием Oracle с именем пользователя username и пароль pwd .
Читайте также: