Как подключить mysql к intellij idea
Перейти к содержимому

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

  • автор:

MySQL

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

On the Data Sources tab in the Data Sources and Drivers dialog, click the Add icon () and select MySQL .

Check if there is a Download missing driver files link at the bottom of the data source settings area. As you click this link, IntelliJ IDEA downloads drivers that are required to interact with a database. The IDE does not include bundled drivers in order to have a smaller size of the installation package and to keep driver versions up-to-date for each IDE version.

You can specify your drivers for the data source if you do not want to download the provided drivers. For more information about creating a database connection with your driver, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

To delete a password, right-click the Password field and select Set Empty .

To ensure that the connection to the data source is successful, click the Test Connection link.

Как подключить MySQL к бесплатной версии Intellij IDEA (community)

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

Статья ориентирована на людей уже знакомых с Java Core и MySQL.

А так же для подключения базы данных к приложению Вам необходимо скачать и перед прочтением статьи установить сервер с официального сайта (Это бесплатно).https://dev.mysql.com/downloads/workbench/

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.

10: Теперь нужно установить драйвер (это быстро) для Вашей БД. Идём на официальный сайт ORACLE ( dev.mysql.com/downloads/connector/j ) и качаем архив. Выберите из списка Platform Independent.

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

Getting Familiar with IntelliJ IDEA — Tutorial for beginner

Before starting, make sure that you have JDK, IntelliJ IDEA and MySQL database server installed on your computer, and read these 2 articles first:

1. Setup MySQL database

table-product-structure

This table has 5 columns: id, name, brand, madein and price. You can create this table by executing the following MySQL script in MySQL Workbench tool:

Note: Later you will see you can even create a database (schema) and tables within the IDE.

2. Create new project

new-java-project

In the next screen, enter project name and location as follows:

projec-name-and-location

Click Finish, and click OK if it asks to create the directory. Then you can see the workspace looks like this:

intellij-workspace

As you can see, the default views include Project, Structure, Terminal, Databases… and IntelliJ IDEA hints the 4 shortcut keys in the center. The workspace looks similar to Eclipse/NetBeans but it intelligently tells you the most frequently needed shortcuts.

3. Connect to MySQL database in IntelliJ IDEA

Click the Database view, then click the + sign at the top left corner, point to Data Source and click MySQL:

new-data-source-mysql

Then in the Data Sources and Drivers dialog, you need to specify database connection information and JDBC driver to use. Type in user, pass and Database name as shown in the following screenshot:

datasource-general-info

And click Driver: MySQL (4) > Go to Driver. Select a version for MySQL JDBC driver as follows:

select-jdbc-driver

Then IntellIJ IDEA automatically downloads the required JAR file (this saves time in finding jar files on the Internet).

download-mysql-jdbc-driver

Here, you need to choose the correct driver class name, e.g. com.mysql.jdbc.Driver for MySQL Connector/J version 5.1.47. Then click OK, the IDE will connect to the database and open the console editor that allows you to type SQL statement directly, as shown in the following screenshot:

database-views

Now, you can experiment database development support in IntelliJ IDEA. Play around with the Database view to see the table structure; type a SELECT statement in the console editor and execute it; see the result set, which is empty because we haven’t inserted any rows to the product table yet.

Note that the Database view allows you to create new database (schema) and tables directly, so you don’t have to use any external database tools. Awesome!

So, as you have seen, IntelliJ IDEA makes it easy to work with a database right inside from the IDE (you don’t have to open any external programs) in just few clicks. That means our productivity is increased.

4. Code a batch insert program

Right click on the src folder in the Project view, and select New > Package:

create-package-menu

Then enter the name for the package, e.g. net.codejava – as shown below:

new-java-package

Click OK to create the package. Then right-click on the package name, select New > Class:

new-class-menu

Enter the name of the new class is BatchInsertApp , as below:

new-java-class

As you can see, IntelliJ IDEA suggests you to create a class (default), interface, enum or annotation – so you can easily change without going one step backward.

Hit Enter to create the class. Then type the word main – you can see the IDE instantly suggests you to create the main method:

main-suggestion

Press Enter to insert the main method. Then type the following initial code for the main method:

The IDE automatically suggests code completion as you type. You can press Ctrl + Space to force the IDE showing code suggestion; and Alter + Enter to show hints.

Now let’s modify the sql variable to write a SQL Insert statement to experiment the auto completion for SQL statement, something as shown below:

sql-auto-completion

You see? It’s very quick and convenient as the IDE hints the table name, field names and other SQL keywords.

Then write the complete code as follows:

While writing the code, try to use the auto completion for try-catch (Press Alt + Enter to show hints and choose action), for loop (type fori ) and print statement (type sout ).

Next, we need to add a dependency of MySQL JDBBC driver to the project, so it can run. Right-click on the project name and click Open Module Settings (or press F4 key).

Then in the Project Structure dialog, under the Modules section, click the + button to add a library from Maven, as shown below:

add-dependency-menu

In the search dialog, type mysql-connector-java and click the search button. Wait for a moment, while the IDE is searching on Maven online repository. Then choose the library mysql-connector-java version 5.1.47, like this:

search-mysql-connector-java

Then check the option Download to and click OK:

download-mysql-jdbc-driver-2

And click OK again to confirm in the Configure Library dialog. Then choose the scope Runtime for the dependency:

dependency-scope-runtime

Click OK to close the Project Structure dialog. As you have seen, IntelliJ IDEA makes it easy to get a JAR file from Maven’s online repository. Even you don’t have to open your browser program.

5. Run the program

run-context-menu

Wait for a few seconds while it is building the project, and you will see the output:

run-output

You see, it prints the output “Running time: 3115” which is the time it took to insert 100 rows into the database. The red line above is a warning message from MySQL JDBC driver, and the exit code 0 indicates that the program terminates normally.

Now, switch to the MySQL console view and execute the SELECT statement again. You will see the data appears in table format like this:

select-rows-from-table

In this view, you can even add new row and commit to the database. Very convenient!

So far you have done your first project using IntelliJ IDEA to get familiar with it. As you experience, IntelliJ is smart and greatly improve developer’s productivity by the ability of doing everything within the IDE itself.

Challenge for you today: Code the 2 nd program that allows the user to search for data in the product table (by name, brand and madein fields).

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

How to connect IntelliJ with local MySQL?

I have been struggling to learn how the localhost MySQL and IntelliJ to connect and program a database related task. Is that Possible? If yes, how to achieve it?

Dharman's user avatar

6 Answers 6

Connecting to a local instance is essentially the same as connecting to a remote instance of MySQL. Just substitute either localhost, or 127.0.0.1 in place of the IP address you would use normally.

To add a new database connection (called a data source in IntelliJ), open the Database window View -> Tool Windows -> Databases, then click the + sign and select Data Source and then MySQL from the sub-menu. The defaults for the MySQL connection should for a local install of MySQL.

To open a connection, right click on your new data source and select Open Console.

As of Community version 2017.2, the DB Browser does not come bundled with the IDE (at least not on my last two installations). In order to activate it, you should navigate in the IDE in **File->Settings->Plugins->Browse repositories and select «Database» from the dropdown menu. From there you can install the Database Navigator. After the installation has been successful, you should restart the IDE . Then you can select **View->Tool windows->DB Browser .

Jack Doe's user avatar

In recent versions of Idea Community (about 2017.3, but I am not sure) there is no Database tool available anymore, only in Idea Ultimate [1]. Yet worse, the plugin Database Navigator that would fit here to solve this problem is not compatible anymore, at least not with 2018.3 [2].

Uninstalling Idea right now, unfortunately.

sdlins's user avatar

To add a new database connection (called a data source in IntelliJ), open the Database window View -> Tool Windows -> Databases, then click the + sign and select Data Source and then MySQL from the sub-menu. The defaults for the MySQL connection should for a local install of MySQL.

To open a connection, right click on your new data source and select Open Console.

to download Drivers click on «Download missing Drivers» in bottom of the window.

if you want to add JDBC and connect other database vendor like workbench projects (instead of using intelliJ Consol) just follow the steps bellow :

Using JDBC drivers #

Create a connection to a database with a JDBC driver # If you cannot find a name of a database vendor in the list of data sources, download a JDBC driver for the database management system (DBMS), and create a connection in IntelliJ IDEA. With the JDBC driver, you can connect to DBMS and start working.

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

In the Data Sources and Drivers dialog, click the Add icon (+) and select Driver and Data Source.

Click the User Driver link.

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

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.

Click Apply.

Return to the created data source connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field. To set an empty password, right-click the Password field and select Set empty.

To ensure that the connection to the data source is successful, click Test Connection.

For more information read the official answer of Jetbrains in following link :

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *