Java MySQL Connection
This section introduces how to connect to a MySQL database using JDBC in Java.
Connecting to MySQL from Java requires a driver package. The latest version can be downloaded from **. After extraction, you will get a JAR library file, which should then be imported into your project.
You can download the JAR package provided by this site: **
This example uses Eclipse to import the JAR package:
>
Database connection for MySQL 8.0 and above is different:
Use the driver package version mysql-connector-java-8.0.16.jar for MySQL 8.0 and above.
Replace com.mysql.jdbc.Driver with
com.mysql.cj.jdbc.Driver
.
MySQL 8.0 and above do not need an SSL connection and must be explicitly turned off.
allowPublicKeyRetrieval=true allows the client to retrieve the public key from the server.
Finally, you also need to set CST.
The method to load the driver and connect to the database is as follows:
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_demo?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","password");
Creating Test Data
Next, we will create a database named tutorialpro
in MySQL and a table named websites
with the following structure:
CREATE TABLE `websites` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(20) NOT NULL DEFAULT '' COMMENT 'Site Name',
`url` varchar(255) NOT NULL DEFAULT '',
`alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa Rank',
`country` char(10) NOT NULL DEFAULT '' COMMENT 'Country',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
Insert some data:
INSERT INTO `websites` VALUES ('1', 'Google', 'https://www.google.cm/', '1', 'USA'), ('2', '淘宝', 'https://www.taobao.com/', '13', 'CN'), ('3', 'tutorialpro.org', 'http://www.tutorialpro.org', '5892', ''), ('4', '微博', 'http://weibo.com/', '20', 'CN'), ('5', 'Facebook', 'https://www.facebook.com/', '3', 'USA');
The table will display as follows:
Connecting to the Database
The following example uses JDBC to connect to a MySQL database. Note that some data such as username and password need to be configured according to your development environment:
MySQLDemo.java File Code:
package com.tutorialpro.test;
import java.sql.*;
public class MySQLDemo {
// JDBC driver name and database URL for MySQL 8.0 and below
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/tutorialpro";
// JDBC driver name and database URL for MySQL 8.0 and above
//static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
//static final String DB_URL = "jdbc:mysql://localhost:3306/tutorialpro?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
// Database username and password, need to set according to your own configuration
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute query
System.out.println("Instantiating Statement object...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// Expand result set database
while (rs.next()) {
// Retrieve by field
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// Output data
System.out.print("ID: " + id);
System.out.print(", Site Name: " + name);
System.out.print(", Site URL: " + url);
System.out.print("\n");
}
// Close after completion
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle JDBC errors
se.printStackTrace();
} catch (Exception e) {
// Handle Class.forName errors
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
} // Do nothing
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
The above example outputs the following results: