Как подключить mysql к intellij idea ubuntu

Обновлено: 04.07.2024

Покажем как подключить базу данных из Microsoft SQL Server 2012 к IDE IntelliJ IDEA, а так же настроить конфигурацию IDE и MS SQL Server.

Используемые технологии:

MS SQL Server 2012

IntelliJ IDEA 14

1. Описание задачи

Для удобства разработки Java приложения, в котором поставщиком данных является база данных Microsoft SQL, можно создать соединение с MS SQL Server 2012 прямо из среды разработки IntelliJ IDEA.

2. База данных в MS SQL 2012

Для начала вам необходимо скачать с официального сайта майкрософт MS SQL Server 2012 Express. Если не хотите разбираться в чем разница, то скачивайте все компоненты для вашей версии системы (64/32бит) и устанавливайте. Во время установки были выбраны настройки по умолчанию и я опущу это описание, т.к. там нет ничего особенного.

Далее была создана БД excelParser . Как видите на скриншоте ниже полный путь к серверу:W156-LOB/SQLEXPRESS. Где первая часть это имя домена, в котором находится этот компьютер (на домашней машине у вас скорее всего этого не будет), а вторая это название сервера, выбранное при установке (по умолчанию).

3. Настройка MS SQL Server в MS SQL Management Studio

Вообще добавлять ещё одного пользователя и менять некоторые настройки должно быть не обязательно, но у меня в связи с корпоративными настройками безопасности, прокси и всяких там других ограничений коннектится к БД с пользователем по умолчанию отказывалось напрочь. Итак:

SQL server authentication settings

Для начала в свойствах сервера выбираем Проверка подлинности SQL Server и Windows . Далее добавляем пользователя:

SQL create User

SQL User role

Дальше необходимо присвоить полные права созданному пользователю. Добавляем галочку в sysadmin во вкладке Роли сервера .

4. Настройка MS SQL Server 2012 Configuration

По умолчанию подсоединиться к серверу можно только через Management Studio, а доступ через TCP/IP в настройках выключен. Следовательно и в IDE подключиться не получится. Заходим в SQL Server Configuration Manager :

Свойства TCPIP MS SQL 12

Dynamic TPC port

SQL Server Config

5. Настройка IntelliJ IDEA

Здесь всё покажу сразу на одном скриншоте:

IDEA MS SQL Connection

IDEA test connection

Примерно такая надпись должна появиться в случае успешного подключения к серверу Microsoft SQL Server 2012 Express.

6. Дополнение

Вам может понадобиться скачать драйвера java ms sql connection. Необходимый набор можно скачать с официального сайта майкрософт или найти в интернете (в том числе и свежие зависимости maven).


Привет, сегодня покажу как подключить Ваше приложение к базе данных (БД) в бесплатной версии Intellij IDEA (community).В статье будет: много картинок, мало букв, будет интересно и полезно.

1: Создаём новый проект в Intellij IDEA

image

2: Затем идём вFile->Settings->Plugins->MarketPlace и в поисковой строке вводим Database Navigator.Устанавливаем, перезапускаем Intellij IDEA.


3: После установки плагина и перезапуска Intellij IDEA, в Вашем ТулБаре появится новое окно (DB Navigator)

4: Заходим в новое окно(DB Navigator), нажимаем зелёный плюсик и из предложенного списка выбираем MySQL


5: В появившемся окне вписываем в поле Name, имя которое вы хотите дать базе данных. Описание можно оставить пустым.Host и Port трогать не нужно. Проследите за тем что бы в поле Database была строка mysql. Вводим User и Password (Обычно это (root) для Логина и Пароля). После всего нажимайте Test Connection.


6: При тестировании соединения может возникнуть ошибка временной зоны. Для её исправления в поиске операционной системы вводим mysql, и выбираем MySQL Command Line Client (всё как на картинке).


7: В появившемся консоле вводим пароль БД, И вводим команду set global time_zone = '+3:00';(+3 часа это мой часовой пояс так как я нахожусь в Минске, вы вводите часовой пояс своего города).


8: После исправления ошибки жмите Apply, Ok и в вашем DB navigator появляется структура БД с которой вы можете просматривать таблицы и БД.


9: Рекомендую при просматривании таблиц нажимать на кнопку No filters.



11: Когда архив загрузился, открываем его и извлекаем файл (смотрите картинку) в папку (путь к папке нужно запомнить).


12: Переходим в Intellij IDEA, там ищем File->Project Structure ->SDK's -> плюсик который отмечен стрелкой -> ищем файл который только что скачали -> жмём ОК.


13: База Данных подключена к Intellij IDEA! Теперь надо разобраться как подключиться к ней через приложение. Для этого я создал класс который назвал TestConnection и в нём прописал константы (USER_NAME, PASSWORD, URL), создал статические Statement и Connection.


14: Кстати что бы найти значение поля URL, нужно открыть Ваш DB Navigator, нажать на зелёный плюс, выбрать mysql(Тут БД может попросить логин и пароль), и в открывшемся окне выбрать Info. Скопировать значение строки Connection URL.Это и будет URL.

15: Осталось немного. Просим у ДрайверМенеджера что бы он дал нам соединение (смотрите картинку ниже, верхний красный блок).Всё должно быть обёрнуто в ТрайКэтч. А в нижнем блоке создаём Statement.


16: Как я уже писал статья ориентирована на людей уже знакомых с языком MySQL. все запросы легко гугляться, язык очень простой и является MustHave(обязательно) для каждого BackEND Developer, поэтому я не буду объяснять что написано на языке SQL (было бы очень долго). Что касается Java:

1 — В главном методе (main) нужно указать ClassPath (первая строка на картинке).
2 — Во втором красном блоке у Statement я вызвал метод executeUpdater. Его нужно использовать для обновления или добавления данных в таблице. Метод, по умолчанию, в параметры принимает строку в которую Вам следует писать ваши SQL-запросы обёрнутый в двойные кавычки.
3 — Добавление данных в таблицу наглядно.
4 — Для получения данных из таблицы я вызвал метод executeQuery у Statement, он так же принимает строку в параметры.
5 — Что бы вывести в консоль данные полученные с таблицы я использую цикл while с параметром (смотрите картинку) который проходит все строки таблицы по очереди, а в теле вызывается метод getString у resulySet (Всё как на картинке). этот метод принимает в параметры цифру которая означает номер колонки которую вы хотите получить.


Какие могут быть ошибки

Хочу рассказать о некоторых ошибках с которыми Вы можете встретиться, конечно вы можете это не читать, но это очень важно.

1 — Если создание таблицы прошло успешно, её следует закомментировать потому что так как таблица уже создана, при следующем запуске приложение вылетит, потому что код начнёт отрабатывать по новой и попытается создать ещё одну таблицу с таки же Name, а это запрещено.

Будет вот такая ошибка. Что значит «Таблица Name уже существует»


2 — Так же и со всеми данными, если они добавлены успешно, следует удалять или комментировать строки которые их добавляли или обновляли.

3 — Будьте внимательны с SQL, Intellij IDEA не подчёркивает ошибки которые вы допускаете в синтаксисе, закрывайте скобки и кавычки. Пример ошибки синтаксиса SQL

When you create a database connection, IntelliJ IDEA connects to a database automatically to receive database objects. Then connection closes. Names of data sources that interact with a database are shown in the Database tool window with a little green circle.

If you want to close a database connection, select a data source and click the Disconnect button on the toolbar. Alternatively, select a data source and press Ctrl+F2 .

Close a database connection

Options for password storage

You can select the following options for storing your password:

Never : password is prompted each time you establish a connection with a database.

Until restart : password is saved only for the current IntelliJ IDEA run. If you exit IntelliJ IDEA and open it again, you must provide the password again.

For session : password is saved only for the current connection session with a database (until you disconnect from it). You can terminate the connection by pressing the Disconnect icon () or Ctrl+F2 .

Forever : password is saved in the IntelliJ IDEA storage. You do not need to provide the password next time you open IntelliJ IDEA.

JDBC drivers

Change the driver version

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

In the Data Sources and Drivers dialog, click the Drivers tab, and select a driver entry that you want to modify.

Click the Driver link in data source settings.

Some data sources have a drop-down list with drivers for different versions (for example, MySQL). In these cases, select Go to driver from the list.

In the Driver files pane, click the version number, and select the driver version that you need.

Configure a JDBC driver from the existing connection

You can add libraries to the existing driver or replace the driver completely.

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

In the Data Sources and Drivers dialog, click the Drivers tab, and select a data source where you want to change a driver.

Click the Driver link in data source settings.

Click the provided driver entry, and click Remove ().

To revert changes, click the Rollback Changes icon () that is in the lower-right part of the window.

In the Driver files pane, click the Add icon () and select Custom JARs .

In the file browser, navigate to the JAR file of the JDBC driver, select it, and click OK .

In the Class field, specify the value that you want to use for the driver .

Add an icon to a user driver

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

Click the Options tab, scroll down to the Other section.

From the Icon list, select an icon that you want to assign to the driver.

Connection options

Keep the connection alive

You can keep the connection to a database alive by running a keep-alive query after the specified period. You can define the custom query in the driver settings for unsupported databases.

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

On the Options tab, select the Run keep-alive query each checkbox and type a number of seconds after which IntelliJ IDEA must run a keep-alive query again.

To set a custom keep-alive query for a driver, select the necessary driver on the Drivers tab. Click the Options tab. In the Keep-alive query field, specify the query that you want to use as a keep-alive query.

Disconnect from a database in a specified period

You can specify a period in seconds after which IntelliJ IDEA terminates the connection.

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

On the Options tab, select the Auto-disconnect after N seconds checkbox, where N is a number of seconds after which IntelliJ IDEA terminates the connection.

Run a predefined query as you establish a connection

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

On the Options tab, in the Startup script field, specify the query that you plan to run on a connection to a database.

Refresh the database state

If someone changed the remote database data or view, the local view of the database might differ from the actual state of the database.

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

On the Options tab, select the Auto sync checkbox.

If the Auto sync checkbox is cleared, the view of the data source in the Database tool window ( View | Tool Windows | Database ) is synchronized with the actual state of the database only when you click the Refresh icon or press Ctrl+F5 .

Filter objects with the object filter

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

On the Schemas tab, type filtering options in the Object filter field.

Use the following pattern when you compose an expression for the Object filter field.

<type> might be an aggregate, collation, event, fdw, ftable, mview, operator, package, role, routine, sequence, synonym, table, user, view, vtable.

<pattern> is a regular expression. To exclude an item, prepend with - (minus). For more information about regular expressions, see Class Patterns at JavaTM 2 Platform Standard Edition 5.0 API Specification.

Filter databases and schemas

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

On the Schemas tab, type filtering options in the Schema pattern field.

@ : the current database or schema.

* : every database or schema. You can list schemas after *: .

Consider the following examples:

*:* : all schemas in all databases.

@:* : all schemas from the current database

@:@ : only the current schema

*:dbo|@:@|db1:s1,s2,s3 : the dbo schema from all databases, the current schema, schemas s1,s2,s3 from the db1 database.

Connection modes

Enable read-only mode for a connection

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

On the Options tab, select the Read-only checkbox.

Single session mode

Single session mode means that the data source and all consoles use one and the same connection. This mode allows you to see the temporary objects in the database tree, or use the same transaction in different query consoles. For more information about query consoles, read Query console.

When you apply single session mode, you must close all existing opened connections. IntelliJ IDEA displays a notification if you have opened connections. To close opened connections for the selected data source, click Yes . To close opened connections for all modified data sources, click Yes for all .

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

On the Data Sources tab, select a data source that you want to modify.

On the Options tab, select Single session mode .

If the Single session mode checkbox is cleared, each new query console creates a new connection.

Single database mode

When you connect to a data source, IntelliJ IDEA can retrieve and display you all the databases that the data source has. But in some cases (for example, with certain settings of PgBouncer), you can or are allowed to work only with a certain database. With the Single database mode enabled, you see in the database tree view only the database that you specified in the connection settings, not all the databases that were received from the data source.

Consider using this setting, for PostgreSQL, Azure SQL Database, Greenplum, Amazon Redshift.

In the Database tool window ( View | Tool Windows | Database ), click the Data Source Properties icon .

В статье будет рассмотрено как создать базу данных MySQL и затем подключиться к ней с помощью среды разработки IntelliJ IDEA.

Используемые технологии:

IntelliJ IDEA 14

1. Описание задачи

Необходимо создать БД MySQL с несколькими таблицами. Затем эта база данных будет использована в проекте Java приложения и поэтому удобно было бы подключиться к ней прямо из среды разработки. Как это сделать, будет показано ниже.

2. Создание схемы и таблиц MySQL

Для удобства работы с MySQL я использую MySQL WorkBench 6.3. CE. Развернуть БД на локальном компьютере и установить необходимые компоненты не представляет труда. Просто зайдите на официальный сайт разработчика, скачайте всё что предлагают и установите. Думаю вам можно выбрать все пункты, которые предлагают разработчики по умолчанию.

MySql1

Теперь открываем вкладку Schemas , правой кнопкой выбираем пункт Create Schema и вводим имя:

MySQL create Schema

Теперь необходимо создать таблицы. Эта БД будет использована в туториале по Hibernate и Spring Data и я заранее создам несколько таблиц, которые будут использованы в том проекте.

mysql contact table

Таблицы можно создать как через графический интерфейс, так и с помощью скрипта:

MySQL create tables

Запросы для создания таблиц:

Таблица с деталями телефона контакта:

, UNIQUE uq_contact_tel_detail_1 ( contact_id , tel_type ) , CONSTRAINT FK_CONTACT_TEL_DETAIL_1 FOREIGN KEY ( contact_id )

Таблица хобби контакта:

, CONSTRAINT FK_CONTACT_HOBBY_DETAIL_1 FOREIGN KEY ( contact_id ) REFERENCES javastudy . contact ( id ) ON DELETE CASCADE , CONSTRAINT FK_CONTACT_HOBBY_DETAIL_2 FOREIGN KEY ( hobby_id )

3. Подключение базы данных MySQL к среде разработки IntelliJ IDEA

Теперь посмотрим как подключить только что созданную схему javastudy к среде разработки. Я создал просто пустой maven проект.

MySQL connection setting

*на всякий случай путь, где лежит драйвер. Обратите внимание, что находится он в скрытой папке .IntelliJIdea14 конкретного пользователя:

  • C:/Users/iMacPC/.IntelliJIdea14/config/jdbc-drivers/mysql-connector-java-5.1.34-bin.jar

Теперь необходимо ввести данные о хосте, имени базы данных, пользователе и пароле. Если вы выбрали все настройки по умолчанию, то данные будут такие же как у меня: Host: localhost , порт 3306 . Имя пользователя и пароль здесь root/admin .

MySQL connection setting 2

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