MySQL Connector/J
MySQL provides connectivity for client applications developed in the Java programming language with MySQL Connector/J, a driver that implements the Java Database Connectivity (JDBC) API and also MySQL X DevAPI.
MySQL Connector/J 9.3 is a JDBC Type 4 driver that is compatible with the JDBC 4.2 specification. The Type 4 designation means that the driver is a pure Java implementation of the MySQL protocol and does not rely on the MySQL client libraries.
The driver also contains an implementation of MySQL X DevAPI, an application programming interface for working with MySQL as a Document Store through CRUD-based, NoSQL operations.
For more information, please visit the official MySQL Connector/J documentation.
Licensing
Please refer to the README and LICENSE files, available in this repository, and the Legal Notices in the MySQL Connector/J documentation for further details.
Security
Oracle values the independent security research community and believes that responsible disclosure of security vulnerabilities helps us ensure the security and privacy of all our users. Please refer to the security guidelines document for additional information.
Getting the Latest Release
MySQL Connector/J is free for usage under the terms of the specified licensing and it runs on any operating system that is able to run a Java Virtual Machine.
Download and Install
MySQL Connector/J can be installed from pre-compiled packages that can be downloaded from the MySQL Connector/J download page. Installing MySQL Connector/J only requires obtaining the corresponding JAR file from the downloaded bundle or installer and including it in the application’s CLASSPATH.
According to how you use MySQL Connector/J, you may also need to install the following third-party libraries on your system for it to work:
- Protocol Buffers (protobuf-java) is required for using X DevAPI.
- Oracle Cloud Infrastructure SDK for Java (oci-java-sdk) is required to support OCI AIM authentication.
- Simple Logging Facade API (slf4j-api) is required for using the logging capabilities provided by the default implementation of org.slf4j.Logger.Slf4JLogger by MySQL Connector/J.
- OpenTelemetry API and SDK are required for enabling OpenTelemetry native instrumentation.
As a Maven Dependency
Alternatively, MySQL Connector/J can be obtained automatically via Maven’s dependency management by adding the following configuration in the application’s Project Object Model (POM) file:
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>9.3.0</version> </dependency>
MySQL Connector/J’s own Project Object Model (POM) file specifies a transitive dependency to Protocol Buffers (protobuf-java) since it is required for using X DevAPI. However, if you do not use the X DevAPI features, you may also want to add a dependency exclusion to avoid linking the unneeded sub-library. For example:
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>9.3.0</version> <exclusions> <exclusion> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> </exclusion> </exclusions> </dependency>
Build From Source
This driver can also be complied and installed from the source available in this repository. Please refer to the MySQL Connector/J documentation for detailed instructions on how to do it.
GitHub Repository
This repository contains the MySQL Connector/J source code as per the latest release. No changes are made in this repository between releases.
Contributing
We greatly appreciate feedback from our users, including bug reports and code contributions. Your input helps us improve, and we thank you for any issues you report or code you contribute. Please refer to the contributing guidelines document for additional information.
Additional Resources
- MySQL Connector/J Developer Guide.
- MySQL Connector/J X DevAPI Reference.
- MySQL Connector/J, JDBC and Java Forum.
#connectors
channel in MySQL Community Slack (Sign-up required if you do not have an Oracle account.)- @MySQL on X.
- MySQL Blog.
- MySQL Connectors Blog archive.
- MySQL Newsletter.
- MySQL Bugs Tracking System.
For more information about this and other MySQL products, please visit MySQL Contact & Questions.
MySQL
Последнее обновление: 08.08.2018
Одной из наиболее популярных СУБД в связке с Java является MySQL. Поэтому рассмотрим, как мы можем работать с MySQL в Java.
Подробнее про работу с MySQL можно посмотреть в соответствующем материале Руководство по MySQL
Для работы с MySql в Java необходимо установить официальный драйвер MySQL Connector/J. Загрузим его с адресса
https://dev.mysql.com/downloads/connector/j/. Распакуем загруженный архив,
найдем там собственно драйвер, который представляет собой файл с расширением jar (на момент написания данной статьи это файл
mysql-connector-java-8.0.11.jar), и положим его в папку программы.
Убедимся, что мы в прицнипе можем осуществлять взаимодействие с MySQL через данный драйвер. Для этого определим следующий код программы:
public class Program{ public static void main(String[] args) { //java -classpath c:\Java\mysql-connector-java-8.0.11.jar;c:\Java Program try{ Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance(); System.out.println("Connection succesfull!"); } catch(Exception ex){ System.out.println("Connection failed..."); System.out.println(ex); } } }
Для загрузки драйвера здесь применяется строка
Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();
Метод Class.forName() в качестве параметра принимает строку, которая представляет полный путь к классу драйвера с учетом
всех пакетов. В случае MySQL это путь «com.mysql.cj.jdbc.Driver». Таким образом, Метод Class.forName загружает класс драйвера, который будет использоваться.
Далее вызывается метод getDeclaredConstructor(), который возвращает конструктор данного класса. И в конце вызывается метод
newInstance(), который создает с помощью конструктора объект данного класса. И после этого мы сможем взаимодействовать с сервером MySQL.
Убедимся, что сервер MySQL запущен, и скомпилируем и запустим программу на выполнение:
C:\Java>javac Program.java C:\Java>java -classpath c:\Java\mysql-connector-java-8.0.11.jar;c:\Java Program Connection succesfull! C:\Java>
В моем случае класс программы и драйвер размещены в папке C:\Java. Поэтому при выполнении программы после параметра -classpath
я указываю полный путь к файлу драйвера — «c:\Java\mysql-connector-java-8.0.11.jar». Далее после точки с запятой указывается каталог, где находятся
файлы программы, то есть опть же это каталог «C:\Java». И после этого идет название выполняемого класса программы — «Program».
И если все сделано правильно, то при выполнении программы мы можем увидеть на консоли строку «Connection succesfull!». После этого мы можем начать
взаимодействовать с MySQL.
СУБД MySQL предоставляет приложениям Java возможность соединения с базой данных при помощи драйвера MySQL Connector, который реализует интерфейс API Java Database Connectivity (JDBC). Этот API является независимым от СУБД стандартом связи языка программирования Java с широким спектром баз данных, электронных таблиц и т.п.
- Введение
- Установка
- Установка Java Connector в Microsoft Windows
- Соединение с MySQL с помощью MySQL Connector/J
- Компиляция и исполнение кода
- Запросы к данным с использованием MySQL Connector/J
- Компиляция и исполнение кода
API JDBC позволяет осуществлять следующие операции:
- Устанавливать соединение с базой данных;
- Выполнять SQL запросы;
- Обрабатывать результаты, полученные из базы данных.
Далее мы узнаем, как установить и настроить MySQL Connector/J (драйвер JDBC ), а также используем его при создании приложения.
Версии MySQL Connector/J:
Версия Connector/J | Версия JDBC | Версия MySQL сервера | Статус |
5.1 | 3.0, 4.0 | 4.1, 5.0, 5.1, 5.5, 5.6, 5.7 | Рекомендуемая версия |
5.0 | 3.0 | 4.1, 5.0 | Выпущенная версия |
3.1 | 3.0 | 4.1, 5.0 | Устаревшая |
3.0 | 3.0 | 3.x, 4.1 | Устаревшая |
Загрузка Connector/J :
MySQL Connector J — это официальный драйвер JDBC для MySQL. Вы можете загрузить последнюю версию драйвера отсюда. Выберите одну из кроссплатформенных версий:
Или версию для Microsoft Windows:
Вы можете установить пакет драйверов Connector/J, используя либо бинарный установочный файл, либо исходный код. Метод с установочным файлом прост, поскольку он представляет собой набор библиотек и прочих скомпилированных файлов.
Метод с использованием исходного кода пригодится, если вы хотите настроить или изменить процесс установки. Помимо этого нужно будет вручную добавить путь к Connector/J в переменную Java classpath.
MySQL Connector/J поставляется как архив .zip или .tar.gz, содержащий файлы исходных классов. После распаковки архива установите драйвер, поместив MySQL-connector-java-version-bin.jar в ваш classpath. Для этого добавьте полный путь к нему в переменную окружения classpath или укажите его в параметре -cp при старте JVM.
Переменную окружения classpath можно установить в системах Unix, Linux или Mac OS X локально для пользователя в его файле .profile, .login или ином login-файле. Или же установить её, изменив глобальный файл /etc/profile.
Например, добавьте драйвер MySQL Connector J ava в переменную classpath с помощью любой из следующих команд в зависимости от используемой оболочки командной строки:
# C shell(csh, tcsh): shell> setenv CLASSPATH /path/MySQL-connector-java-ver-bin.jar:$CLASSPATH
В Windows 2000, Windows XP, Windows Server 2003 и Windows Vista можно установить переменную окружения в панели управления.
Выберите и загрузите нужный вам установщик здесь.
Затем выполните следующие шаги:
Шаг 1:
Дважды щёлкните по файлу установщика.
Шаг 2:
Нажмите ‘Run‘ и дождитесь завершения процесса.
Приведенный ниже пример MySQL Connector показывает, как соединиться с базой данных, разорвать соединение и обработать ошибки.
Версия Java 7 Update 25 (сборка 1.7.0_25-b16):
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class test { public static void main (String[] args) { System.out.println("nn***** MySQL JDBC Connection Testing *****"); Connection conn = null; try { Class.forName ("com.MySQL.jdbc.Driver").newInstance (); String userName = "root"; String password = "pqrs123"; String url = "jdbc:MySQL://localhost/sakila"; conn = DriverManager.getConnection (url, userName, password); System.out.println ("Database Connection Established..."); } catch (Exception ex) { System.err.println ("Cannot connect to database server"); ex.printStackTrace(); } finally { if (conn != null) { try { System.out.println("n***** Let terminate the Connection *****"); conn.close (); System.out.println ("Database connection terminated... "); } catch (Exception ex) { System.out.println ("Error in connection termination!"); } } } } }
Пояснение :
Чтобы создать jdbc-подключение к базе данных c помощью MySQL Connector ODBC, нужно импортировать следующие пакеты из java.sql:
- sql.Connection;
- sql.DriverManager;
- sql.SQLException;
Далее мы создаём класс ‘test‘ и метод main.
Приведенный ниже код создаёт соединение с базой данных:
conn = DriverManager.getConnection (url, userName, password);
Класс JDBC DriverManager определяет объекты, которые могут соединять приложения Java с драйвером JDBC. Этот класс включает в себя метод getConnection(). Он использует url-адрес jdbc, имя пользователя и пароль, чтобы установить соединение с базой данных, и возвращает объект подключения.
В коде, приведенном выше, мы использовали следующие url-адрес, имя пользователя и пароль:
- Строка url «jdbc:MySQL://localhost/sakila», в которой первая часть — «jdbc:MySQL://localhost» — это тип базы данных (в данном случае MySQL ) и сервер (в данном случае — localhost ). Остальная часть — название базы данных (в данном случае — ‘sakila‘).
- Имя пользователя MySQL определяется в переменной ‘userName ‘.
- Пароль для MySQL определяется в переменной ‘password‘.
DriverManager пытается соединиться с базой данных. Если соединение проходит успешно, создаётся объект Connection (сохраняется в переменной ‘conn’) и программа отображает сообщение “Database Connection Established…” (“Соединение с базой данных установлено…”).
Если попытка соединения c помощью MySQL Connector оканчивается неудачей (например, если указан неверный пароль, адрес сервера и т.п.), тогда нужно обработать эту ситуацию. Мы ловим эту ошибку в блоке catch выражения try … catch, отображаем соответствующие сообщения и в конце закрываем соединение.
Предположим, что файл ‘test.java’ находится на диске E:, а ‘MySQL-connector-java-5.1.31-bin.jar’ хранится в «C:Program FilesMySQLMySQL Connector J«.
Примечание: Путь class path – это путь, по которому Java Runtime Environment (JRE) ищет классы и другие файлы ресурсов. Можно изменить этот путь, используя опции -classpath или -cp некоторых команд Java, когда вы вызываете JWM или другие инструменты JDK, или изменив переменную окружения classpath.
Предположим, что мы хотим получить имена (first_name, last_name) и размер зарплаты (salary) работников, которые получают больше средней зарплаты и работают в ИТ-отделе.
Структура базы данных ‘hr’:
Пример таблицы ‘работники’ (‘employees ’):
+-------------+-------------+-------------+----------+--------------------+------------+------------+----------+----------------+------------+---------------+ | EMPLOYEE_ID | FIRST_NAME | LAST_NAME | EMAIL | PHONE_NUMBER | HIRE_DATE | JOB_ID | SALARY | COMMISSION_PCT | MANAGER_ID | DEPARTMENT_ID | +-------------+-------------+-------------+----------+--------------------+------------+------------+----------+----------------+------------+---------------+ | 100 | Steven | King | SKING | 515.123.4567 | 1987-06-17 | AD_PRES | 24000.00 | 0.00 | 0 | 90 | | 101 | Neena | Kochhar | NKOCHHAR | 515.123.4568 | 1987-06-18 | AD_VP | 17000.00 | 0.00 | 100 | 90 | | 102 | Lex | De Haan | LDEHAAN | 515.123.4569 | 1987-06-19 | AD_VP | 17000.00 | 0.00 | 100 | 90 | | 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 1987-06-20 | IT_PROG | 9000.00 | 0.00 | 102 | 60 | | 104 | Bruce | Ernst | BERNST | 590.423.4568 | 1987-06-21 | IT_PROG | 6000.00 | 0.00 | 103 | 60 | | 105 | David | Austin | DAUSTIN | 590.423.4569 | 1987-06-22 | IT_PROG | 4800.00 | 0.00 | 103 | 60 | | 106 | Valli | Pataballa | VPATABAL | 590.423.4560 | 1987-06-23 | IT_PROG | 4800.00 | 0.00 | 103 | 60 | | 107 | Diana | Lorentz | DLORENTZ | 590.423.5567 | 1987-06-24 | IT_PROG | 4200.00 | 0.00 | 103 | 60 | | 108 | Nancy | Greenberg | NGREENBE | 515.124.4569 | 1987-06-25 | FI_MGR | 12000.00 | 0.00 | 101 | 100 | | 109 | Daniel | Faviet | DFAVIET | 515.124.4169 | 1987-06-26 | FI_ACCOUNT | 9000.00 | 0.00 | 108 | 100 | | 110 | John | Chen | JCHEN | 515.124.4269 | 1987-06-27 | FI_ACCOUNT | 8200.00 | 0.00 | 108 | 100 | | 111 | Ismael | Sciarra | ISCIARRA | 515.124.4369 | 1987-06-28 | FI_ACCOUNT | 7700.00 | 0.00 | 108 | 100 | | 112 | Jose Manuel | Urman | JMURMAN | 515.124.4469 | 1987-06-29 | FI_ACCOUNT | 7800.00 | 0.00 | 108 | 100 | | 113 | Luis | Popp | LPOPP | 515.124.4567 | 1987-06-30 | FI_ACCOUNT | 6900.00 | 0.00 | 108 | 100 | | 114 | Den | Raphaely | DRAPHEAL | 515.127.4561 | 1987-07-01 | PU_MAN | 11000.00 | 0.00 | 100 | 30 | | 115 | Alexander | Khoo | AKHOO | 515.127.4562 | 1987-07-02 | PU_CLERK | 3100.00 | 0.00 | 114 | 30 | | 116 | Shelli | Baida | SBAIDA | 515.127.4563 | 1987-07-03 | PU_CLERK | 2900.00 | 0.00 | 114 | 30 | | 117 | Sigal | Tobias | STOBIAS | 515.127.4564 | 1987-07-04 | PU_CLERK | 2800.00 | 0.00 | 114 | 30 | | 118 | Guy | Himuro | GHIMURO | 515.127.4565 | 1987-07-05 | PU_CLERK | 2600.00 | 0.00 | 114 | 30 | | 119 | Karen | Colmenares | KCOLMENA | 515.127.4566 | 1987-07-06 | PU_CLERK | 2500.00 | 0.00 | 114 | 30 | | 120 | Matthew | Weiss | MWEISS | 650.123.1234 | 1987-07-07 | ST_MAN | 8000.00 | 0.00 | 100 | 50 | | 121 | Adam | Fripp | AFRIPP | 650.123.2234 | 1987-07-08 | ST_MAN | 8200.00 | 0.00 | 100 | 50 | | 122 | Payam | Kaufling | PKAUFLIN | 650.123.3234 | 1987-07-09 | ST_MAN | 7900.00 | 0.00 | 100 | 50 | | 123 | Shanta | Vollman | SVOLLMAN | 650.123.4234 | 1987-07-10 | ST_MAN | 6500.00 | 0.00 | 100 | 50 | | 124 | Kevin | Mourgos | KMOURGOS | 650.123.5234 | 1987-07-11 | ST_MAN | 5800.00 | 0.00 | 100 | 50 | | 125 | Julia | Nayer | JNAYER | 650.124.1214 | 1987-07-12 | ST_CLERK | 3200.00 | 0.00 | 120 | 50 | | 126 | Irene | Mikkilineni | IMIKKILI | 650.124.1224 | 1987-07-13 | ST_CLERK | 2700.00 | 0.00 | 120 | 50 | | 127 | James | Landry | JLANDRY | 650.124.1334 | 1987-07-14 | ST_CLERK | 2400.00 | 0.00 | 120 | 50 | | 128 | Steven | Markle | SMARKLE | 650.124.1434 | 1987-07-15 | ST_CLERK | 2200.00 | 0.00 | 120 | 50 | | 129 | Laura | Bissot | LBISSOT | 650.124.5234 | 1987-07-16 | ST_CLERK | 3300.00 | 0.00 | 121 | 50 | | 130 | Mozhe | Atkinson | MATKINSO | 650.124.6234 | 1987-07-17 | ST_CLERK | 2800.00 | 0.00 | 121 | 50 | | 131 | James | Marlow | JAMRLOW | 650.124.7234 | 1987-07-18 | ST_CLERK | 2500.00 | 0.00 | 121 | 50 | | 132 | TJ | Olson | TJOLSON | 650.124.8234 | 1987-07-19 | ST_CLERK | 2100.00 | 0.00 | 121 | 50 | | 133 | Jason | Mallin | JMALLIN | 650.127.1934 | 1987-07-20 | ST_CLERK | 3300.00 | 0.00 | 122 | 50 | | 134 | Michael | Rogers | MROGERS | 650.127.1834 | 1987-07-21 | ST_CLERK | 2900.00 | 0.00 | 122 | 50 | | 135 | Ki | Gee | KGEE | 650.127.1734 | 1987-07-22 | ST_CLERK | 2400.00 | 0.00 | 122 | 50 | | 136 | Hazel | Philtanker | HPHILTAN | 650.127.1634 | 1987-07-23 | ST_CLERK | 2200.00 | 0.00 | 122 | 50 | | 137 | Renske | Ladwig | RLADWIG | 650.121.1234 | 1987-07-24 | ST_CLERK | 3600.00 | 0.00 | 123 | 50 | | 138 | Stephen | Stiles | SSTILES | 650.121.2034 | 1987-07-25 | ST_CLERK | 3200.00 | 0.00 | 123 | 50 | | 139 | John | Seo | JSEO | 650.121.2019 | 1987-07-26 | ST_CLERK | 2700.00 | 0.00 | 123 | 50 | | 140 | Joshua | Patel | JPATEL | 650.121.1834 | 1987-07-27 | ST_CLERK | 2500.00 | 0.00 | 123 | 50 | | 141 | Trenna | Rajs | TRAJS | 650.121.8009 | 1987-07-28 | ST_CLERK | 3500.00 | 0.00 | 124 | 50 | | 142 | Curtis | Davies | CDAVIES | 650.121.2994 | 1987-07-29 | ST_CLERK | 3100.00 | 0.00 | 124 | 50 | | 143 | Randall | Matos | RMATOS | 650.121.2874 | 1987-07-30 | ST_CLERK | 2600.00 | 0.00 | 124 | 50 | | 144 | Peter | Vargas | PVARGAS | 650.121.2004 | 1987-07-31 | ST_CLERK | 2500.00 | 0.00 | 124 | 50 | | 145 | John | Russell | JRUSSEL | 011.44.1344.429268 | 1987-08-01 | SA_MAN | 14000.00 | 0.40 | 100 | 80 | | 146 | Karen | Partners | KPARTNER | 011.44.1344.467268 | 1987-08-02 | SA_MAN | 13500.00 | 0.30 | 100 | 80 | | 147 | Alberto | Errazuriz | AERRAZUR | 011.44.1344.429278 | 1987-08-03 | SA_MAN | 12000.00 | 0.30 | 100 | 80 | | 148 | Gerald | Cambrault | GCAMBRAU | 011.44.1344.619268 | 1987-08-04 | SA_MAN | 11000.00 | 0.30 | 100 | 80 | | 149 | Eleni | Zlotkey | EZLOTKEY | 011.44.1344.429018 | 1987-08-05 | SA_MAN | 10500.00 | 0.20 | 100 | 80 | | 150 | Peter | Tucker | PTUCKER | 011.44.1344.129268 | 1987-08-06 | SA_REP | 10000.00 | 0.30 | 145 | 80 | | 151 | David | Bernstein | DBERNSTE | 011.44.1344.345268 | 1987-08-07 | SA_REP | 9500.00 | 0.25 | 145 | 80 | | 152 | Peter | Hall | PHALL | 011.44.1344.478968 | 1987-08-08 | SA_REP | 9000.00 | 0.25 | 145 | 80 | | 153 | Christopher | Olsen | COLSEN | 011.44.1344.498718 | 1987-08-09 | SA_REP | 8000.00 | 0.20 | 145 | 80 | | 154 | Nanette | Cambrault | NCAMBRAU | 011.44.1344.987668 | 1987-08-10 | SA_REP | 7500.00 | 0.20 | 145 | 80 | | 155 | Oliver | Tuvault | OTUVAULT | 011.44.1344.486508 | 1987-08-11 | SA_REP | 7000.00 | 0.15 | 145 | 80 | | 156 | Janette | King | JKING | 011.44.1345.429268 | 1987-08-12 | SA_REP | 10000.00 | 0.35 | 146 | 80 | | 157 | Patrick | Sully | PSULLY | 011.44.1345.929268 | 1987-08-13 | SA_REP | 9500.00 | 0.35 | 146 | 80 | | 158 | Allan | McEwen | AMCEWEN | 011.44.1345.829268 | 1987-08-14 | SA_REP | 9000.00 | 0.35 | 146 | 80 | | 159 | Lindsey | Smith | LSMITH | 011.44.1345.729268 | 1987-08-15 | SA_REP | 8000.00 | 0.30 | 146 | 80 | | 160 | Louise | Doran | LDORAN | 011.44.1345.629268 | 1987-08-16 | SA_REP | 7500.00 | 0.30 | 146 | 80 | | 161 | Sarath | Sewall | SSEWALL | 011.44.1345.529268 | 1987-08-17 | SA_REP | 7000.00 | 0.25 | 146 | 80 | | 162 | Clara | Vishney | CVISHNEY | 011.44.1346.129268 | 1987-08-18 | SA_REP | 10500.00 | 0.25 | 147 | 80 | | 163 | Danielle | Greene | DGREENE | 011.44.1346.229268 | 1987-08-19 | SA_REP | 9500.00 | 0.15 | 147 | 80 | | 164 | Mattea | Marvins | MMARVINS | 011.44.1346.329268 | 1987-08-20 | SA_REP | 7200.00 | 0.10 | 147 | 80 | | 165 | David | Lee | DLEE | 011.44.1346.529268 | 1987-08-21 | SA_REP | 6800.00 | 0.10 | 147 | 80 | | 166 | Sundar | Ande | SANDE | 011.44.1346.629268 | 1987-08-22 | SA_REP | 6400.00 | 0.10 | 147 | 80 | | 167 | Amit | Banda | ABANDA | 011.44.1346.729268 | 1987-08-23 | SA_REP | 6200.00 | 0.10 | 147 | 80 | | 168 | Lisa | Ozer | LOZER | 011.44.1343.929268 | 1987-08-24 | SA_REP | 11500.00 | 0.25 | 148 | 80 | | 169 | Harrison | Bloom | HBLOOM | 011.44.1343.829268 | 1987-08-25 | SA_REP | 10000.00 | 0.20 | 148 | 80 | | 170 | Tayler | Fox | TFOX | 011.44.1343.729268 | 1987-08-26 | SA_REP | 9600.00 | 0.20 | 148 | 80 | | 171 | William | Smith | WSMITH | 011.44.1343.629268 | 1987-08-27 | SA_REP | 7400.00 | 0.15 | 148 | 80 | | 172 | Elizabeth | Bates | EBATES | 011.44.1343.529268 | 1987-08-28 | SA_REP | 7300.00 | 0.15 | 148 | 80 | | 173 | Sundita | Kumar | SKUMAR | 011.44.1343.329268 | 1987-08-29 | SA_REP | 6100.00 | 0.10 | 148 | 80 | | 174 | Ellen | Abel | EABEL | 011.44.1644.429267 | 1987-08-30 | SA_REP | 11000.00 | 0.30 | 149 | 80 | | 175 | Alyssa | Hutton | AHUTTON | 011.44.1644.429266 | 1987-08-31 | SA_REP | 8800.00 | 0.25 | 149 | 80 | | 176 | Jonathon | Taylor | JTAYLOR | 011.44.1644.429265 | 1987-09-01 | SA_REP | 8600.00 | 0.20 | 149 | 80 | | 177 | Jack | Livingston | JLIVINGS | 011.44.1644.429264 | 1987-09-02 | SA_REP | 8400.00 | 0.20 | 149 | 80 | | 178 | Kimberely | Grant | KGRANT | 011.44.1644.429263 | 1987-09-03 | SA_REP | 7000.00 | 0.15 | 149 | 0 | | 179 | Charles | Johnson | CJOHNSON | 011.44.1644.429262 | 1987-09-04 | SA_REP | 6200.00 | 0.10 | 149 | 80 | | 180 | Winston | Taylor | WTAYLOR | 650.507.9876 | 1987-09-05 | SH_CLERK | 3200.00 | 0.00 | 120 | 50 | | 181 | Jean | Fleaur | JFLEAUR | 650.507.9877 | 1987-09-06 | SH_CLERK | 3100.00 | 0.00 | 120 | 50 | | 182 | Martha | Sullivan | MSULLIVA | 650.507.9878 | 1987-09-07 | SH_CLERK | 2500.00 | 0.00 | 120 | 50 | | 183 | Girard | Geoni | GGEONI | 650.507.9879 | 1987-09-08 | SH_CLERK | 2800.00 | 0.00 | 120 | 50 | | 184 | Nandita | Sarchand | NSARCHAN | 650.509.1876 | 1987-09-09 | SH_CLERK | 4200.00 | 0.00 | 121 | 50 | | 185 | Alexis | Bull | ABULL | 650.509.2876 | 1987-09-10 | SH_CLERK | 4100.00 | 0.00 | 121 | 50 | | 186 | Julia | Dellinger | JDELLING | 650.509.3876 | 1987-09-11 | SH_CLERK | 3400.00 | 0.00 | 121 | 50 | | 187 | Anthony | Cabrio | ACABRIO | 650.509.4876 | 1987-09-12 | SH_CLERK | 3000.00 | 0.00 | 121 | 50 | | 188 | Kelly | Chung | KCHUNG | 650.505.1876 | 1987-09-13 | SH_CLERK | 3800.00 | 0.00 | 122 | 50 | | 189 | Jennifer | Dilly | JDILLY | 650.505.2876 | 1987-09-14 | SH_CLERK | 3600.00 | 0.00 | 122 | 50 | | 190 | Timothy | Gates | TGATES | 650.505.3876 | 1987-09-15 | SH_CLERK | 2900.00 | 0.00 | 122 | 50 | | 191 | Randall | Perkins | RPERKINS | 650.505.4876 | 1987-09-16 | SH_CLERK | 2500.00 | 0.00 | 122 | 50 | | 192 | Sarah | Bell | SBELL | 650.501.1876 | 1987-09-17 | SH_CLERK | 4000.00 | 0.00 | 123 | 50 | | 193 | Britney | Everett | BEVERETT | 650.501.2876 | 1987-09-18 | SH_CLERK | 3900.00 | 0.00 | 123 | 50 | | 194 | Samuel | McCain | SMCCAIN | 650.501.3876 | 1987-09-19 | SH_CLERK | 3200.00 | 0.00 | 123 | 50 | | 195 | Vance | Jones | VJONES | 650.501.4876 | 1987-09-20 | SH_CLERK | 2800.00 | 0.00 | 123 | 50 | | 196 | Alana | Walsh | AWALSH | 650.507.9811 | 1987-09-21 | SH_CLERK | 3100.00 | 0.00 | 124 | 50 | | 197 | Kevin | Feeney | KFEENEY | 650.507.9822 | 1987-09-22 | SH_CLERK | 3000.00 | 0.00 | 124 | 50 | | 198 | Donald | OConnell | DOCONNEL | 650.507.9833 | 1987-09-23 | SH_CLERK | 2600.00 | 0.00 | 124 | 50 | | 199 | Douglas | Grant | DGRANT | 650.507.9844 | 1987-09-24 | SH_CLERK | 2600.00 | 0.00 | 124 | 50 | | 200 | Jennifer | Whalen | JWHALEN | 515.123.4444 | 1987-09-25 | AD_ASST | 4400.00 | 0.00 | 101 | 10 | | 201 | Michael | Hartstein | MHARTSTE | 515.123.5555 | 1987-09-26 | MK_MAN | 13000.00 | 0.00 | 100 | 20 | | 202 | Pat | Fay | PFAY | 603.123.6666 | 1987-09-27 | MK_REP | 6000.00 | 0.00 | 201 | 20 | | 203 | Susan | Mavris | SMAVRIS | 515.123.7777 | 1987-09-28 | HR_REP | 6500.00 | 0.00 | 101 | 40 | | 204 | Hermann | Baer | HBAER | 515.123.8888 | 1987-09-29 | PR_REP | 10000.00 | 0.00 | 101 | 70 | | 205 | Shelley | Higgins | SHIGGINS | 515.123.8080 | 1987-09-30 | AC_MGR | 12000.00 | 0.00 | 101 | 110 | | 206 | William | Gietz | WGIETZ | 515.123.8181 | 1987-10-01 | AC_ACCOUNT | 8300.00 | 0.00 | 205 | 110 | +-------------+-------------+-------------+----------+--------------------+------------+------------+----------+----------------+------------+---------------+
Код SQL:
SELECT first_name, last_name, salary FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE department_name LIKE 'IT%') AND salary > (SELECT avg(salary) FROM employees);
Далее следует код Java (версия 7 Update 25 (сборка 1.7.0_25-b16)) с использованием MySQL Connector J:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.ResultSet; public class testsql { public static void main (String[] args) { Connection conn = null; try { Class.forName ("com.MySQL.jdbc.Driver").newInstance (); String userName = "root"; String password = "datasoft123"; String url = "jdbc:MySQL://localhost/hr"; conn = DriverManager.getConnection (url, userName, password);
// Блок запроса SQL -> Начало здесь Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT first_name, last_name, salary FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE department_name LIKE 'IT%') AND salary > (SELECT avg(salary) FROM employees)"); // Запрашиваем данные из запроса System.out.println ("n-------------SQL DATA-------------n"); while(rs.next()) { //Получаем по имени столбца String fname = rs.getString("first_name"); String lname = rs.getString("last_name"); int salary = rs.getInt("Salary"); //Отображаем значения System.out.print("Name " + fname+' '+lname); System.out.print(",Salary: " + salary); } System.out.println ("nn-------------END-------------n"); } catch (SQLException ex){ // обрабатываем ошибки System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } // игнорируем ошибку rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { } // игнорируем ошибку stmt = null; } } // Блок SQL запроса заканчивается здесь } catch (Exception ex) { System.err.println ("Cannot connect to database server"); ex.printStackTrace(); } finally { if (conn != null) { try { // System.out.println("n***** Let terminate the Connection *****"); conn.close (); // System.out.println ("nnDatabase connection terminated..."); } catch (Exception ex) { System.out.println ("Error in connection termination!"); } } } } }
Предположим, что файл ‘testsql.java ’ находится на диске E:, а ‘MySQL-connector-java-5.1.31-bin.jar ‘ хранится в «C:Program FilesMySQLMySQL Connector J» .
Примечание: Путь class path – это путь к MySQL Connector Java, по которому Java Runtime Environment (JRE ) ищет классы и другие файлы ресурсов. Можно изменить этот путь, используя опции -classpath или -cp некоторых команд Java, когда вы вызываете JWM или другие инструменты JDK, либо изменив переменную окружения classpath.
Сергей Бензенкоавтор-переводчик статьи «MySQL Java Connector»
is not current version
Last Version 8.0.29 →
JDBC Type 4 driver for MySQL
Categories |
Categories Java |
---|---|
GroupId |
GroupIdmysql |
ArtifactId |
ArtifactIdmysql-connector-java |
Version |
Version8.0.22 |
Type |
Typejar |
Download mysql-connector-java 8.0.22
Apache Maven
<!-- https://jarcasting.com/artifacts/mysql/mysql-connector-java/ -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
Gradle Groovy
// https://jarcasting.com/artifacts/mysql/mysql-connector-java/
implementation 'mysql:mysql-connector-java:8.0.22'
Gradle Kotlin
// https://jarcasting.com/artifacts/mysql/mysql-connector-java/
implementation ("mysql:mysql-connector-java:8.0.22")
Apache Buildr
'mysql:mysql-connector-java:jar:8.0.22'
Apache Ivy
<dependency org="mysql" name="mysql-connector-java" rev="8.0.22">
<artifact name="mysql-connector-java" type="jar" />
</dependency>
Groovy Grape
@Grapes(
@Grab(group='mysql', module='mysql-connector-java', version='8.0.22')
)
Scala SBT
libraryDependencies += "mysql" % "mysql-connector-java" % "8.0.22"
Leiningen
[mysql/mysql-connector-java "8.0.22"]
Java Connector
MySQL provides connectivity for Java client applications with MySQL Connector/J, a driver that implements the Java Database Connectivity (JDBC) API. The API is the industry standard for database-independent connectivity between the Java programming language and a wide range of SQL databases, spreadsheets etc. The JDBC API can do the following things :
- Establish a connection with a database or access any tabular data source.
- Send SQL statements.
- Retrieve and process the results received from the database.
In the following section, we have discussed how to install, configure, and develop database applications using MySQL Connector/J (JDBC driver).
MySQL Connector/J version :
Connector/J version |
JDBC version |
MySQL Server version |
Status |
---|---|---|---|
5.1 | 3.0, 4.0 | 4.1, 5.0, 5.1, 5.5, 5.6, 5.7 | Recommended version |
5.0 | 3.0 | 4.1, 5.0 | Released version |
3.1 | 3.0 | 4.1, 5.0 | Obsolete |
3.0 | 3.0 | 3.x, 4.1 | Obsolete |
Download Connector/J :
MySQL Connector/J is the official JDBC driver for MySQL. You can download the latest version of MySQL Connector/J binary or source distribution from the following web site —
http://dev.MySQL.com/downloads/connector/j/
For Platform Independent select any one from the following :
For Microsoft Windows :
Installation
You can install the Connector/J package drivers using either the binary, binary installation or source installation. The binary method is easy which is a bundle of necessary libraries and other files pre-built, with an installer program. The source installation method is important where you want to customize or modifies the installation process or for those platforms where a binary installation package is not available. Apart from that solution, you manually add the Connector/J location to your Java classpath.
MySQL Connector/J is distributed as a .zip or .tar.gz archive containing the sources, the class files. After extracting the distribution archive, you can install the driver by placing MySQL-connector-java-version-bin.jar in your classpath, either by adding the full path to it to your classpath environment variable or by directly specifying it with the command line switch -cp when starting the JVM.
You can set the classpath environment variable under Unix, Linux or Mac OS X either locally for a user within their .profile, .login or another login file. You can also set it globally by editing the global /etc/profile file.
For example add the Connector/J driver to your classpath using one of the following forms, depending on your command shell :
# Bourne-compatible shell (sh, ksh, bash, zsh): shell> export CLASSPATH=/path/MySQL-connector-java-ver-bin.jar:$CLASSPATH # C shell(csh, tcsh): shell> setenv CLASSPATH /path/MySQL-connector-java-ver-bin.jar:$CLASSPATH
In Windows 2000, Windows XP, Windows Server 2003 and Windows Vista, you can set the environment variable through the System Control Panel.
Install Java Connector on Microsoft Windows
Select and download the MSI installer packages from http://dev.MySQL.com/downloads/connector/j/ as per your requirement.
Now follow the following steps :
Step -1 :
Double click the installer (here it is «MySQL-connector-java-gpl-5.1.31.msi»)
Step -2 :
Click on ‘Run’ and complete the process.
Connecting to MySQL using MySQL Connector/J
The following example shows how to connect/terminate and handle errors. (Java version 7 Update 25 (build 1.7.0_25-b16))
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class test
{
public static void main (String[] args)
{
System.out.println("\n\n***** MySQL JDBC Connection Testing *****");
Connection conn = null;
try
{
Class.forName ("com.MySQL.jdbc.Driver").newInstance ();
String userName = "root";
String password = "pqrs123";
String url = "jdbc:MySQL://localhost/sakila";
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("\nDatabase Connection Established...");
}
catch (Exception ex)
{
System.err.println ("Cannot connect to database server");
ex.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
System.out.println("\n***** Let terminate the Connection *****");
conn.close ();
System.out.println ("\nDatabase connection terminated...");
}
catch (Exception ex)
{
System.out.println ("Error in connection termination!");
}
}
}
}
}
Explanation:
To create a java jdbc connection to the database, you must import the following java.sql package.
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
Now we will make a class named ‘test’ and then the main method.
To create a connection to a database, the code is :
conn = DriverManager.getConnection (url, userName, password);
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is the backbone of the JDBC architecture. The DriverManager has a method called getConnection(). The method uses a jdbc url, username and a password to establish a connection to the database and returns a connection object. We have used the following url, username and password in the above code.
- The url string is «jdbc:MySQL://localhost/sakila» where the first part «jdbc:MySQL://localhost» is the database type (here it is MySQL) and server (here it is localhost). Rest part is the database name (here it is ‘sakila’).
- The user name for MySQL is defined inside the variable ‘userName’.
- The password for MySQL is defined inside the variable ‘password’.
The DriverManager attempts to connect to the database, if the connection is successful, a Connection object is created, (here it is called ‘conn’) and the program will display a message «Database Connection Established…»
If the connection fails (e.g. supplying wong password, host address etc.) then you need to handle the situation. We are trapping the error in catch part of the try … catch statement with appropriate messages and finally close the connection.
Compile and Run it
Assume that ‘test.java’ is stored in E:\ and ‘MySQL-connector-java-5.1.31-bin.jar’ is stored in «C:\Program Files\MySQL\MySQL Connector J\».
Note : The class path is the path that the Java Runtime Environment (JRE) searches for classes and other resource files. You can change the class path by using the -classpath or -cp option of some Java commands when you call the JVM or other JDK tools or by using the classpath environment variable.
Querying data using MySQL Connector/J
Suppose we want to get the names (first_name, last_name), salary of the employees who earn more than the average salary and who works in any of the IT departments.
Structure of ‘hr’ database :
Sample table : employees
SQL Code :
SELECT first_name, last_name, salary
FROM employees
WHERE department_id IN
(SELECT department_id FROM departments WHERE department_name LIKE 'IT%')
AND salary > (SELECT avg(salary) FROM employees);
Here is the Java Code (version 7 Update 25 (build 1.7.0_25-b16))
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class testsql
{
public static void main (String[] args)
{
Connection conn = null;
try
{
Class.forName ("com.MySQL.jdbc.Driver").newInstance ();
String userName = "root";
String password = "datasoft123";
String url = "jdbc:MySQL://localhost/hr";
conn = DriverManager.getConnection (url, userName, password);
// Run SQL -> start from here
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT first_name, last_name, salary FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE department_name LIKE 'IT%') AND salary > (SELECT avg(salary) FROM employees)");
// Extract data from result set
System.out.println ("\n-------------SQL DATA-------------\n");
while(rs.next()){
//Retrieve by column name
String fname = rs.getString("first_name");
String lname = rs.getString("last_name");
int salary = rs.getInt("Salary");
//Display values
System.out.print("Name " + fname+' '+lname);
System.out.print(",Salary: " + salary);
}
System.out.println ("\n\n-------------END-------------\n");
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
}
// SQL end at here
}
catch (Exception ex)
{
System.err.println ("Cannot connect to database server");
ex.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
///System.out.println("\n***** Let terminate the Connection *****");
conn.close ();
// System.out.println ("\n\nDatabase connection terminated...");
}
catch (Exception ex)
{
System.out.println ("Error in connection termination!");
}
}
}
}
}
Compile and Run it
Assume that ‘testsql.java’ is stored in E:\ and ‘MySQL-connector-java-5.1.31-bin.jar’ is stored in «C:\Program Files\MySQL\MySQL Connector J\».
Note : The class path is the path that the Java Runtime Environment (JRE) searches for classes and other resource files. You can change the class path by using the -classpath or -cp option of some Java commands when you call the JVM or other JDK tools or by using the classpath environment variable.
Previous: MySQL Python Connector
Next: MySQL Storage Engines (table types)