Dbeaver как подключиться к базе oracle

Обновлено: 06.07.2024

Rapidly create and deploy powerful Java applications that integrate with Oracle databases.

Manage Oracle data with visual tools in DBeaver like the query browser.

The CData JDBC Driver for Oracle implements JDBC standards that enable third-party tools to interoperate, from wizards in IDEs to business intelligence tools. This article shows how to connect to Oracle data with wizards in DBeaver and browse data in the DBeaver GUI.

Create a JDBC Data Source for Oracle Data

Follow the steps below to load the driver JAR in DBeaver.

  1. Open the DBeaver application and, in the Databases menu, select the Driver Manager option. Click New to open the Create New Driver form.
  2. In the Driver Name box, enter a user-friendly name for the driver.
  3. To add the .jar, click Add File.
  4. In the create new driver dialog that appears, select the cdata.jdbc.oracleoci.jar file, located in the lib subfolder of the installation directory.
  5. Click the Find Class button and select the OracleOCIDriver class from the results. This will automatically fill the Class Name field at the top of the form. The class name for the driver is cdata.jdbc.oracleoci.OracleOCIDriver.
  6. Add jdbc:oracleoci: in the URL Template field.

Create a Connection to Oracle Data

Follow the steps below to add credentials and other required connection properties.

  1. In the Databases menu, click New Connection.
  2. In the Create new connection wizard that results, select the driver.
  3. On the next page of the wizard, click the driver properties tab.

Enter values for authentication credentials and other properties required to connect to Oracle.

To connect to Oracle, you'll first need to update your PATH variable and ensure it contains a folder location that includes the native DLLs. The native DLLs can be found in the lib folder inside the installation directory. Once you've done this, set the following to connect:

  • Port: The port used to connect to the server hosting the Oracle database.
  • User: The user Id provided for authentication with the Oracle database.
  • Password: The password provided for authentication with the Oracle database.
  • Service Name: The service name of the Oracle database.

Built-in Connection String Designer

For assistance in constructing the JDBC URL, use the connection string designer built into the Oracle JDBC Driver. Either double-click the JAR file or execute the jar file from the command-line.

java -jar cdata.jdbc.oracleoci.jar

Fill in the connection properties and copy the connection string to the clipboard.


Below is a typical connection string:

Query Oracle Data

You can now query information from the tables exposed by the connection: Right-click a Table and then click Edit Table. The data is available on the Data tab.


CData Software is a leading provider of data access and connectivity solutions. Our standards-based connectors streamline data access and insulate customers from the complexities of integrating with on-premise or cloud databases, SaaS, APIs, NoSQL, and Big Data.

DBeaver is a free, open source multiplatform database management tool and SQL client for developers and database administrators. DBeaver can be used to access any database or cloud application that has an ODBC or JDBC driver, such as Oracle, SQL Server, MySQl, Salesforce, or MailChimp. Devart DBeaver provides you with the most important features you'd need when working with a database in a GUI tool, such as:

  • SQL queries execution
  • Metadata browsing and editing
  • SQL scripts management
  • Data export/import
  • Data backup
  • DDL generation
  • ER diagrams rendering
  • Test data generation
  • BLOB/CLOB support
  • Database objects browsing
  • Scrollable resultsets

The tool comes in two editions — Community and Enterprise. Enterprise Edition supports NoSQL databases, such as MongoDB or Cassandra, persistent query manager database, SSH tunneling, vector graphics (SVG) and a few other enterprise-level features. Note though that you can access a MongoDB database from DBeaver Community Edition using the respective Devart ODBC driver. For the purposes of this guide, we'll use the Community Edition of DBeaver to retrieve data from MySQL via the Open Database Connectivity driver.

Creating an ODBC Data Source to Use MySQL Data in DBeaver

  1. Click the Start menu and select Control Panel.
  2. Select Administrative Tools, then click ODBC Data Sources.
  3. Click on the System DSN tab if you want to set up a DSN name for all users of the system or select User DSN to configure DSN only for your account.
  4. Click the Add button and double-click Devart ODBC Driver for MySQL in the list.
  5. Give a name to your data source and set up the connection parameters.
  6. Click the Test Connection button to verify that you have properly configured the DSN.

When using ODBC driver for MySQL with DBeaver, SQL_WVARCHAR data types may be displayed incorrectly in DBeaver. To prevent this, you need to set the string data types to Ansi either in the Advanced Settings tab of the driver configuration dialog or directly in the connection string (String Types=Ansi) — all string types will be returned as SQL_CHAR, SQL_VARCHAR and SQL_LONGVARCHAR.

Using in DBeaver

Connecting to MySQL Data from DBeaver via ODBC Driver for MySQL

Follow the steps below to establish a connection to MySQL in DBeaver.

    In the Database menu, select New Database Connection.

New Database Connection for MySQL in DBeaver

Select ODBC Data Source in DBeaver

DBeaver ODBC Connection Settings

Viewing MySQL Database Objects and Querying Data

You can expand out the database structure in DBeaver's Database Navigator to visualize all the tables in MySQL database. To view and edit the data in a table, you need to right-click on the target table name and select View data.The content of the table will be displayed in the main workspace.

Retrieve data from MySQL in DBeaver

If you want to write a custom SQL query that will include only the necessary columns from the table, you can select New SQL Editor in the SQL Editor main menu. Create your query and run it by clicking Execute SQL Statement to view the results in the same window.

DBeaver provides a wizard that guides you through the steps to create a connection. If you run DBeaver for the first time (standalone version), the new connection wizard appears automatically. In other cases, to create a connection, do one of the following:

Click the New Connection Wizard button in the application toolbar or in the Database Navigator view toolbar:

Click Database -> New Connection in the menu bar:


Press Ctrl+N or click File -> New in the menu bar:



Then, in the wizard, click Database connection and then click Next:


Then, in the Create new connection wizard:

Choose a driver for the new connection: click the name of the suitable database type in the gallery. Then click Next.


To quickly find the needed driver, you can type a hint in the text field above the list of drivers.
If you cannot find a driver for your database then probably there is no suitable driver and you need to create one. Please see Database Drivers article.

NOTE: The list of database drivers diaplays the number of exising connections next to each driver. No number is displayed if there are no connections.

If you prefer the classic list view of the available drivers, use the Classic button.


You can choose the Simple mode on this step. Simple mode gives simplified access to the database, which is basically with the ability to view data only in schemas and tables.


In the Connection Settings screen, on the General tab, set all primary connection settings:


For most drivers required settings include:

  • Host
  • Port
  • Database name
  • User name and password

However, the number and type of connection properties are very dependent on the driver.
For example, embedded drivers (such as SQLite, Derby Embedded, HSQLDB, H2 Embedded), unlike remote ones, require only the path to the database.

If necessary, specify advanced settings, see Advanced Settings section below, and click Next.

Network Settings (SSH, SOCKS, SSL)

If your database cannot be accessed directly, you can use SSH tunnel:


DBeaver supports following SSH authentication methods: user/password, public key authentication and agent authentication. Supported implementations for agent authentications are pageant and ssh-agent.

If a connection has network settings specified, such a connection appears in the application with a special 'arrow' icon such as this:

More information about SSH configuration can be found on SSH configuration page.

Connection Details (name, type, etc.)

You can also set the connection name, type and initial settings (such as bootstrap queries, transaction state, global filters, etc.).


Driver Properties

Each driver has its own set of additional properties. Refer to the driver documentation to get information about available properties and their values.


You can use variables in all connection parameters and in the driver properties. Variables are system environment variables or one of the following list:

NameValue
$ Host name
$ Port number
$ Database name
$ Server name
$ Connection URL
$ User name
$ User password

Note: option Use environment variables in connection parameters must be turned on (see preferences).

Обзор очень полезного инструмента для работы с различными базами данных - MySQL, PostgreSQL, Firebird, SQLite, ODBC, Oracle и другими. DBeaver - это свободный кроссплатформенный менеджер баз данных для Linux, Windows и MacOS. О DBeaver кратко: много возможностей, небольшой вес, портабельность, свободное ПО.

Предисловие

При работе под Linux рано или поздно у разработчика или администратора возникнет необходимость в использовании удобного и мультифункционального менеджера баз данных. Это должен быть многофункциональный и и удобный программный продукт, по возможности портабельный и желательно кроссплатформенный, принадлежать к категории свободного ПО - Open Source.

DBeaver - функциональный и удобный кроссплатформенный менеджер баз данных

После недолгих поисков и перебрав несколько вариантов решил остановиться на DBeaver (Database Beaver, Бобер - повелитель Баз Данных). Такой себе универсальный зверек, который проникнет в любую структуру в базе данных и покажет вам что внутри, поможет навести порядок, внести изменения и предоставит прочие полезности и удобства.

Особенности DBeaver

Из основных особенностей программы можно выделить:

  • Удобный структурированный интерфейс, основан на OpenSource фреймворке c большой подборкой мощных плагинов;
  • Небольшой вес - 50Мб;
  • Свободное программное обеспечение;
  • Мультиплатформенность (работает под Linux, MacOS, Windows, Solaris, AIX, HPUX);
  • Поддержка большого количества разных Баз Данных;
  • Умеет делать туннелирование через SSH (встроенный функционал, очень удобно);

Список поддерживаемых баз данных:

  • MySQL;
  • Oracle;
  • PostgreSQL;
  • IBM DB2;
  • Microsoft SQL Server;
  • Sybase;
  • ODBC;
  • Java DB (Derby);
  • Firebird (Interbase);
  • HSQLDB;
  • SQLite;
  • Mimer;
  • H2;
  • IBM Informix;
  • SAP MAX DB;
  • Cache;
  • Ingres;
  • Linter;
  • Teradata;
  • Vertica;
  • MongoDB;
  • Cassandra;
  • Любой JDBC совместимый источник.

Небольшой список того что умеет DBeaver:

  1. Обзор и правка метаданных: таблички, колонки, ключи, индексы;
  2. Выполнение SQL запросов и скриптов;
  3. Подсветка синтаксиса для SQL (специфичная для разных типов БД);
  4. Функция авто-дополнения в SQL редакторе;
  5. Просмотр и редактирование данных в таблицах;
  6. Поддержка BLOB/CLOB (просмотр и редактирование);
  7. Экспорт данных (таблици, результаты запросов);
  8. Менеджмент транзакций;
  9. Поиск объектов в базе данных (таблици, колонки, процедуры и т.п.);
  10. Генерация диаграмм для структур БД;
  11. Закладки для запросов и объектов в БД;
  12. Менеджмент удаленных и локальных подключений;
  13. Экспорт и Импорт в/из БД/файл;
  14. Поиск данных в базе;
  15. И многие другие возможности.

Установка

На странице вы найдете ссылки для скачивания под разные платформы, а также для скачивания исходного кода программы. Есть две версии DBeaver:

  1. Community Edition;
  2. Enterprise Edition.

Обе они являются бесплатными, разница лишь в том что у Enterprise Edition есть поддержка NoSQL баз данных, таких как MongoDB и Cassandra.

Для использования программы в портабельном режиме с помещением ее на переносной носитель, лучше всего ее скачать в виде архива. Например для Линукс жмем по ссылке - "Linux 64 bit (zip archive)".

Использование программы

Приведу пример запуска под Linux. Скачиваем файл по ссылке "Linux 64 bit (zip archive)" браузером или при помощи Wget. Вес архива получился примерно

Распаковываем его при помощи Dolphin'а, файлового менеджера Krusader или в консоли используя unzip, 7zip (команда "7z x имя_файла.zip").

DBeaver - распакованные файлы и папки

Запускаем бинарный файл "dbeaver". После того как программа загрузится будет предложено создать новое подключение к нужной вам базе данных.

Вот как выглядит DBeaver при работе с базой данных в Linux:

Работа с базой данных в Linux использу DBeaver

Все окна можно расположить в удобном вам порядке, для этого их нужно просто перетащить в нужную вам позицию. На примере ниже я выполнил небольшую реорганизацию окон интерфейса DBeaver, а потом в автоматическом режиме сгенерировал диаграмму для базы данных "wordpress":

Диаграмма базы данных wordpress в DBeaver

Для выполнения запросов нужно выбрать активную БД и вызвать редактор SQL-кода, ввести нужный запрос и клацнуть иконку "Execute statement" на панели инструментов или же нажать сочетание клавиш Ctrl+Enter:

Выполнение SQL запроса в DBeaver

Если в окне редактора SQL-кода поместить несколько команд и попробовать их запрустить также как выше - то это не сработает. Для запуска нескольких команд (скрипта) нужно нажать другую кнопочку на панели инструментов - "Execute Script".

Немного поигравшись с интерфейсом вы быстро разберетесь что и к чему, все очень удобно.

Как изменить язык интерфейса программы

Для своего интерфейса программа DBeaver автоматически использует тот язык, который установлен у вас по умолчанию в системе. К примеру, если у вас установлена англоязычная версия Debian GNU/Linux, то интерфейс программы будет также на английском.

Как сменить язык интерфейса в DBeaver на русский или другой язык? - как оказалось все очень просто, нужно передать название предпочитаемой локали как параметр при запуске бинарного файла 'dbeaver'. Вот пример запуска программы с интерфейсом на русском языке:

Здесь предполагается что вы находитесь в консоли в каталоге, где распакован DBeaver. Вот что получим в результате:

DBeaver - интерфейс переключен на русский язык

Для удобства запуска с русскоязычным интерфейсом - создайте ярлык с командой запуска и опцией как приведено выше.

Заключение

Разобравшись с DBeaver вы получите верного помощника для всех дел, касающихся работы с базами данных. Эта программа будет служить и одинаково выполнять свои функции под разными операционными системами, справляться с задачами для различных типов баз данных, предоставляя все свои возможности в удобном и интуитивно-понятном интерфейсе.

А еще эта прекрасная программа является свободным ПО! Вы можете свободно пользоваться ею, делиться с друзьями, а также помогать разработчикам в ее развитии.

Читайте также: