Connect to MySQL using Java JDBC
Mac OS
Java 8.0
MySQL 5.7.27
connector 8.0.17
Install MySQL
Option 1. Visit MySQL website to download https://dev.mysql.com/downloads/connector/j
Option 2. Use Homebrew which is a free and open-source software package management system that simplifies the installation of software on Apple's macOS.
Decompress the file. We will use file mysql-connector-java-8.0.17.jar
Connecting to JDBC
IntelliJ - File - Project Structure (⌘ + ;) - Libraries - Java
Select mysql-connector-java-8.0.17.jar - Open
Press OK then JDBC is connected
Run MySQL
Open Terminal - "mysql.server start"
"mysql -uroot -p" and enter password
Type "exit" or "quit" to exit the mysql shell To shut down MySQL type "mysql.server stop"
Back to IntelliJ to connect to MySQL.
Source Code
package customList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
Connection conn = null;
try {
//for mysql 8.0, use "serverTimezone=UTC" to prevent error
//"&allowPublicKeyRetrieval=true" to prevent Public Key Retrieval is not allowed error
String url = "jdbc:mysql://localhost:3306?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true";
conn = DriverManager.getConnection(url, "root", "1234");
System.out.println(conn.toString());
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
er
|
To prevent "Public Key Retrieval is not allowed" error, add below line
allowPublicKeyRetrieval=true
Reference
https://lhc9138.tistory.com/63
https://www.dev2qa.com/how-to-fix-mysql-jdbc-08001-database-connection-error/