MySQL Maven Java Tutorial
In this tutorial, we use the MySQL Connector/J driver. It is the official JDBC driver for MySQL. The examples were created and tested on Ubuntu Linux. You might also want to check Spring JdbcTemplate tutorial
JDBC
JDBC is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. From a technical point of view, the API is as a set of classes in the java.sql package. To use JDBC with a particular database, we need a JDBC driver for that database.
JDBC是Java编程语言的API,用于定义客户端如何访问数据库。它提供了查询和更新数据库中数据的方法。JDBC面向关系数据库。从技术角度来看,API是java.sql包中的一组类。要将JDBC与特定数据库一起使用,我们需要该数据库的JDBC驱动程序
JDBC is a cornerstone for database programming in Java. Today, it is considered to be very low-level and prone to errors. Solutions such as MyBatis or JdbcTemplate were created to ease the burden of JDBC programming. However, under the hood, these solutions still use JDBC. JDBC is part of the Java Standard Edition platform.
JDBC是Java数据库编程的基石。如今,它被认为是非常底层的,并且容易出错。因此创建了诸如MyBatis或JdbcTemplate之类的解决方案来减轻JDBC编程的负担。但是,实际上,这些解决方案仍然使用JDBC。JDBC是Java Standard Edition平台的一部分。
JDBC manages these three main programming activities:
-
connecting to a database;
-
sending queries and update statements to the database;
向数据库发送查询和更新语句
-
retrieving and processing the results received from the database in answer to the query.
检索并处理从数据库接收到的结果以响应查询
MySQL Connector/J
To connect to MySQL in Java, MySQL provides MySQL Connector/J, a driver that implements the JDBC API. MySQL Connector/J is a JDBC Type 4 driver. 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. In this tutorial, we use MySQL Connector/J 8.0.20, which is a maintenance release of the 8.0 production branch.
为了让Java连接到MySQL,MySQL提供了MySQL Connector/J,它是实现JDBC API的驱动程序。MySQL Connector/J是JDBC Type 4驱动程序。Type 4表示驱动程序是MySQL协议的纯Java实现,并且不依赖MySQL客户端库。在本教程中,使用MySQL Connector / J 8.0.20,它是8.0生产分支的维护版本。
Connection string
A database connection is defined with a connection string. It contains information such as database type, database name, server name, and port number. It also may contain additional key/value pairs for configuration. Each database has its own connection string format.
使用连接字符串定义数据库连接。它包含诸如数据库类型,数据库名称,服务器名称和端口号之类的信息。它还可能包含用于配置的其它键/值对。每个数据库都有其自己的连接字符串格式
The following is a syntax of a MySQL connection string:
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]]
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
It is possible to specify multiple hosts for a server failover setup. The items in square brackets are optional. If no host is specified, the host name defaults to localhost. If the port for a host is not specified, it defaults to 3306, the default port number for MySQL servers.
可以为服务器故障转移设置指定多个主机。方括号中的项目是可选的。如果未指定主机,则主机名默认为localhost。如果未指定主机端口,则默认为MySQL服务器的默认端口号3306
jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC
This is an example of a MySQL connection string. The jdbc:mysql://
is known as a sub-protocol and is constant for MySQL. We connect to the localhost
on MySQL standard port 3306. The database name is testdb
. The additional key/value pairs follow the question mark character (?). The useSSL=false
tells MySQL that there will be no secure connection.
这是一个MySQL连接字符串的示例。jdbc:mysql:// 被称为子协议,对于MySQL来说它是常量。我们在MySQL标准端口3306上连接到本地主机。数据库名称为testdb。其他键/值对在问号字符(?)之后。useSSL = false告诉MySQL将没有安全连接
Setting up MySQL
In this section, we are going to install MySQL server, create a testdb
database, and a test user.
$ sudo apt-get install mysql-server
This command installs the MySQL server and various other packages. While installing the package, we are prompted to enter a password for the MySQL root account.
Next, we are going to create a new database user and a new database. We use the mysql
client.
$ sudo service mysql status
mysql start/running, process 5129
We check if the MySQL server is running. If not, we need to start the server. On Ubuntu Linux, this can be done with the sudo service mysql start
command.
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 43
Server version: 8.0.20-0ubuntu0.18.04.3 (Ubuntu)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
+--------------------+
2 rows in set (0.00 sec)
We use the mysql monitor client application to connect to the server. We connect to the database using the root account. We show all available databases with the SHOW DATABASES
statement.
mysql> CREATE DATABASE testdb;
Query OK, 1 row affected (0.02 sec)
We create a new testdb
database. We will use this database throughout the tutorial.
mysql> CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'test623';
Query OK, 0 rows affected (0.00 sec)
mysql> USE testdb;
Database changed
mysql> GRANT ALL ON testdb.* TO 'testuser'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> quit;
Bye
We create a new database user. We grant all privileges to this user for all tables of the testdb database.
Maven file
We use the following Maven file:
POM.XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zetcode</groupId>
<artifactId>AppName</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<!-- <executions>-->
<!-- <execution>-->
<!-- <goals>-->
<!-- <goal>java</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<configuration>
<mainClass>com.zetcode.JdbcMySQLVersion</mainClass>
<cleanupDaemonThreads>false</cleanupDaemonThreads>
</configuration>
</plugin>
</plugins>
</build>
<name>AppName</name>
</project>
The POM file has a dependency for the MySQL driver. We also include the exec-maven-plugin
for executing Java programs from Maven. Between the `` tags we provide the full name of the application.
POM文件具有MySQL驱动程序的依赖关系。此外,还包括了exec-maven-plugin,用于从Maven执行Java程序。在
Java MySQL version
If the following program runs OK, then we have everything installed OK. We check the version of the MySQL server.
JdbcMySQLVersion.java
package com.zetcode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JdbcMySQLVersion {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC";
String user = "testuser";
String password = "test623";
String query = "SELECT VERSION()";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
We connect to the database and get some info about the MySQL server.
连接到数据库并获取有关MySQL服务器的一些信息
String url = "jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC";
This is the connection URL for the MySQL database. Each driver has a different syntax for the URL. In our case, we provide a host, a port, and a database name.
它是MySQL数据库的连接URL。每个驱动程序对于URL都有不同的语法。在本例中,提供了主机,端口和数据库名称
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
We establish a connection to the database, using the connection URL, user name, and password. The connection is established with the getConnection()
method.
使用连接URL,用户名和密码从而建立与数据库的连接。使用getConnection()方法
The createStatement()
method of the connection object creates a Statement
object for sending SQL statements to the database.
连接对象的createStatement()方法创建一个Statement对象,用于将SQL语句发送到数据库
The executeQuery()
method of the connection object executes the given SQL statement, which returns a single ResultSet
object. The ResultSet
is a table of data returned by a specific SQL statement.
连接对象的executeQuery()方法执行给定的SQL语句,该语句返回单个ResultSet对象。ResultSet是由特定SQL语句返回的数据表
The try-with-resources
syntax ensures that the resources are cleaned up in the end.
try-with-resources语法可确保最后清理资源
if (result.next()) {
System.out.println(result.getString(1));
}
A ResultSet
object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next()
method moves the cursor to the next row. If there are no rows left, the method returns false
. The getString()
method retrieves the value of a specified column. The first column has index 1.
ResultSet对象维护一个游标,该游标指向其当前数据行。最初,光标位于第一行之前。next()方法将光标移动到下一行。如果没有剩余的行,则该方法返回false。getString()方法检索指定列的值。第一列的索引为1
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
In case of an exception, we log the error message. For this console example, the message is displayed in the terminal.
如果发生异常,将记录错误消息。对于此控制台示例,该消息显示在终端中
$ mvn exec:java -q
8.0.20
We run the program from the command line. The Manen's -q
option runs Maven in quiet mode; i.e. we only see error messages.
从命令行运行程序。Manen的-q选项在安静模式下运行Maven。即只会看到错误消息