Перейти к содержимому

Как добавить jdbc драйвер в проект intellij idea

  • автор:

Как подключить JDBC драйвер в Intellij IDEA?

Начал изучать SQl, в качестве подопытной СУБД выбрал PostgreSQL. В процессе подготовки выявилась одна проблема — не пойму как подключить драйвер, программа ни как не хочет увидеть его класс, хотя в драйвере он лежит. Библиотеку драйвера импортировал, в модулях поставил галочку над Export, а работать все-равно не хочет. Драйвер скачивал с офф. сайта, версия 41 так как вроде написано что она под Java 8. Помогите разобраться куда надо ткнуть чтобы оно заработало, не зря же я книги покупал. 🙁 Для проверки работа-способности использую следующий код:

public class Eye < public static void main(String[] args) < try < Class.forName("org.posgresql.Driver"); System.out.println("Driver loading success!"); >catch (ClassNotFoundException e) < e.printStackTrace(); >> 

После компиляции выдает следующее:

java.lang.ClassNotFoundException: org.posgresql.Driver at java.net.URLClassLoader$1.run(URLClassLoader.java:372) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:360) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:259) at Eye.main(Eye.java:8) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) 

Process finished with exit code 0

Как подключить Microsoft SQL Server к Intellij Idea Ultimate

Всем привет! Это моя первая статья в жизни, поэтому в ней может быть много неточностей. Мои знания в программирования слабы, но у меня получилось решить проблему, о которой мало что было написано на просторах интернета (либо я плохо искал). Но надеюсь статья вам поможет =)

Подготовительный этап

В данном туториале мы подключаемся к библиотеке JDBC. Нам потребуется следующее:
1) Intellij Idea Ultimate
2) SQL Server Management Studio (SSMS)
3) Драйвер JDBC, который мы разархивируем в Program Files
4) SQL Server Configuration Manager

Настройка проекта в Intellij Idea

Первое, что нужно сделать, добавить зависимость в pom.xml:

 com.microsoft.sqlserver mssql-jdbc 11.2.2.jre11 

Настройка SQL Server Management Studio

Запускаем SSMS и создаём нового пользователя:

Во вкладке «Общие» задаём какое-нибудь имя пользователю и пароль, при этом, чтобы галочка стояла у «Проверка подлинности SQL Server»:

Далее переходим во вкладку «Роли сервера» и ставим галочку возле «sysadmin»:

Ещё заходим в свойства своего сервера:

Во вкладке «Безопасность» ставим галочку у «Проверки подлинности SQL Server и Windows»:

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

CREATE DATABASE example; USE example GO CREATE TABLE first ( ID INT PRIMARY KEY IDENTITY(1,1), Num INT NOT NULL )

Настройка SQL Server Configuration Manager

Дальше мы будем производить настройку в Configuration Manager, но заранее оговорюсь, что я не уверен наверняка, нужны ли все шаги, которые будут описаны ниже.
1) Переходим в «Протоколы для MSSQLSERVER» и включаем все протоколы:

2) Переходим в свойства TCP/IP и ставим настройки, как на рисунке ниже:

3) Далее вкладка «IP-адреса». Вот здесь есть неточность. Я приведу все скриншоты настроек, которые у меня есть, но может оказаться так, что что-то может быть не необходимым. Но наверняка скажу, что IP4 нужен.

В IP11 и IP12 я ставил TCP-порт 1433 и в строчке «Включено» установил параметр «Да»:

Для настройки IP4 нужно поменять IP-адрес. Заходите на какой-либо ресурс, к примеру этот, и выписываете:

В IPALL я вписал TCP-порт, а значение в «Динамических TCP-портах» потом подставилось само:

Настройка Брандмауэра

Данный этап, возможно, является необязательным, но всё же упомяну его. В ходе работы встречалась ошибка, где компилятор ругался на брандмауэр, поэтому для его решения есть полезная ссылка. Все шаги подробно расписаны, поэтому я не буду расписывать данный этап. Но единственное, на данном сайте написано про порт 80, вместо него мы пишем порт 1433. Вот ссылка.

Подключение базы данных

Заходим в Intellij Idea и переходим, как показано на рисунке:

Хост ставим localhost, порт = 1433. Имя пользователя, пароль и имя БД пишем свои:

После ввода нажимаем на «Test Connection»:

ВНИМАНИЕ. У вас может появиться данная ошибка:

Для её решения переходим в SSMS в свойства данного пользователя и в полях «Пароль», «Подтверждение пароля», «Старый пароль» пишем тот же пароль, что мы устанавливали ранее для данного пользователя и нажимаем ОК. (Чтобы показать ошибку, я создал другого пользователя).

Проделываем процедуру по подключению выше и вуаля, всё работает:

Нажимаем Apply и ОК. Выбираем нашу подключенную БД и нажимаем Ctrl+F5:

После этого мы можем подключить нашу БД через код

За подключение БД отвечает следующий кусочек кода, прописанный в классе. Ваши данные вписываете в нужные поля (DBName, user, pass):

private val connection: Connection init < Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") val connectionUrl = "jdbc:sqlserver://localhost:1433;encrypt=true;database=DBName;trustServerCertificate=true;" connection = DriverManager.getConnection(connectionUrl, "user", "pass") >

Заключение

Спасибо за прочтение. Надеюсь, кому-то это помогло =)

Как подключить драйвер MySQL к проекту в IDEA?

В общем пытаюсь подключиться к БД MySQL через код программы:

package com.company;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Main

public static void main(String[] args) throws SQLException sql_class.sql_query();
>
>

class sql_class public static void sql_query() throws SQLException Connection cn = DriverManager.getConnection(«jdbc:mysql://localhost:3306/testphones»,»admin», «admin»);
Statement st = cn.createStatement();
>
>

но выводит ошибку в консоли:

Exception in thread «main» java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testphones
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.company.sql_class.sql_query(Main.java:16)
at com.company.Main.main(Main.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

В книге написано что нужно скинуть драйвер в папку с проектом в папку lib. Скачал с интернета драйвер но ничего не помогло.
P.S. MySQL установлен через Denwer.

ef449e4d50924067bb71ee46e599ecf0.jpg

P.P.S. сконектилось через DataSourse отлично но не работает соединение через код

  • Вопрос задан более трёх лет назад
  • 6457 просмотров

6 комментариев

Оценить 6 комментариев

PostgreSQL

This functionality relies on the Database Tools and SQL plugin, which is bundled and enabled in IntelliJ IDEA by default. If the relevant features aren’t available, make sure that you didn’t disable the plugin.

The Database Tools and SQL plugin is available only in IntelliJ IDEA Ultimate.

  1. Press Control+Alt+S to open the IDE settings and then select Plugins .
  2. Open the Installed tab, find the Database Tools and SQL plugin, and select the checkbox next to the plugin name.

Official documentation and software

  • For full information about PostgreSQL, refer to the official documentation.
  • To download PostgreSQL database software, refer to the official software downloads.

This topic presents a general procedure on how you can create a data source for the connection to your PostgreSQL database in IntelliJ IDEA, and run a test connection. It is assumed that you already have the necessary prerequisites and the database is up and running. For example, if you want to run a database on your machine and connect to that database, the corresponding DBMS software must be installed on the machine first.

Connect to a PostgreSQL database

Create a new data source

  1. To connect to the database, create a data source that will store your connection details. You can do this using one of the following ways:
    • From the main menu, navigate to File | New | Data Source and select PostgreSQL .
    • In the Database tool window ( View | Tool Windows | Database ) , click the New icon () in the toolbar. Navigate to Data Source and select PostgreSQL .
  2. In the General tab of Data Sources and Drivers dialog right pane, specify the driver and connection type.
    1. In the Driver list, leave the default driver option, unless another driver is required for your connection.
    2. From the Connection type list, select the connection type depending on the connection details that you have:
      • default : connect by using Host , Port , Database , and URL .
      • URL only : connect by using only the URL .

    For the URL only connection type, the JDBC URL that you enter is used as is.

    For the other connection types, the JDBC URL is broken down into connection details. You can either specify them separately and use the automatically generated URL, or you can enter the URL directly in the corresponding field.

General tab of the Data Sources and Drivers dialog

  • Check if there is a Download missing driver files link at the bottom of the connection settings area. Click this link to download drivers that are required to interact with a database. For a direct download link, refer to the JetBrains JDBC drivers page. Location for the downloaded JDBC drivers is the IntelliJ IDEA configuration directory. The Download missing driver files linkYou can also use your drivers for the database instead of the provided ones. For more information about connecting to a database with your driver, refer to Add a user driver to an existing connection. If there is no Download missing driver files link, then you already have the required drivers.
  • Specify the database connection details. Alternatively, paste the JDBC URL in the URL field.

    the Set Empty context menu action

    1. In the Host field, type your server address.
    2. In the Port field, type the port of PostgreSQL. The default port is 5432. Real port numbers might be different on your system. Verify that you use a correct port number with your database administrator, server settings, or hosting provider.
    3. From the Authentication list, select the authentication method that you want to use to authenticate the connection. The following options are available:
      • pgpass : by using the pgpass file. You can store this file in the user’s home directory. You can read more about the password file and its location in The Password File at postgresql.org.
      • User & Password : by using your login and password.
      • No auth : authentication is not required.
    4. In the User and Password fields, type your user credentials. To use no password, leave the Password field empty. To delete a once entered password, right-click the Password field and select Set Empty .
    5. In the Database field, type the database name to which you want to connect.
    6. In the URL field, IntelliJ IDEA generates the JDBC URL automatically using the values of other connection settings. If you need to use a JDBC URL with certain additional settings, paste it in the URL field. The general URL to use is as follows:
      • Format: jdbc:postgresql://:/
      • Example: jdbc:postgresql://127.0.0.1:5432/myDatabase

    For more information about the URL format, refer to the PostgreSQL official documentation.

    Database connection details

    1. From the Authentication list, select the authentication method that you want to use to authenticate the connection. The following options are available:
      • User & Password : by using your login and password.
      • No auth : authentication is not required.
    2. In the User and Password fields, type your user credentials. To use no password, leave the Password field empty. To delete a once entered password, right-click the Password field and select Set Empty . the Set Empty context menu action
    3. In the URL field, IntelliJ IDEA generates the JDBC URL automatically using the values of other connection settings. If you need to use a JDBC URL with certain additional settings, paste it in the URL field. For more information about the URL format, refer to the PostgreSQL official documentation.

    Database connection details

    For the reference information about connection settings and properties on the General and other tabs of Data Sources and Drivers dialog ( Shift+Enter ), see Connection settings and DBMS-specific properties.

  • Ensure that the connection to the database can be established using the provided details. To do that, click the Test Connection link at the bottom of the connection details area. Test Connection linkIn case of any connection issues, refer to the Cannot connect to a database page.
  • (Optional) By default, only the default database and schema are introspected and available to work with. If you also want to work with other databases and schemas, in the Schemas tab, select them for the introspection. Schemas tab of the Data Sources and Drivers dialog
  • Click OK to create the data source.
  • Find your new data source in the Database tool window ( Shortcut is missing ) .
    • For more information about the Database tool window, see the corresponding reference topic. To see more databases and schemas under your new data source node, click the N of M button and select the ones you need. IntelliJ IDEA will introspect and show them. Select databases and schemas to introspect and display in the Database tool window
    • For more information about working with database objects in IntelliJ IDEA, refer to Database objects.
    • To write and run queries, open the default query console by clicking the data source and pressing F4 .
    • To view and edit data of a database object, open Data editor and viewer by double-clicking the object.
  • Connection settings and DBMS-specific properties

    Connection settings

    For the reference information about connection settings (for example, Host , Port , and so on) on the General and other tabs of Data Sources and Drivers dialog ( Shift+Enter ), see Data source settings.

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

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