티스토리 뷰

JAVA

Connect to MySQL using Java JDBC

seoca 2019. 7. 31. 03:19

 

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://stackoverflow.com/questions/50379839/connection-java-mysql-public-key-retrieval-is-not-allowed

https://lhc9138.tistory.com/63

https://coderwall.com/p/os6woq/uninstall-all-those-broken-versions-of-mysql-and-re-install-it-with-brew-on-mac-mavericks

https://www.dev2qa.com/how-to-fix-mysql-jdbc-08001-database-connection-error/

https://whitepaek.tistory.com/category/macOS

'JAVA' 카테고리의 다른 글

Access ArrayList from another class  (0) 2019.08.01
The server time zone Error  (0) 2019.07.31
Java is Pass-By-Value  (0) 2019.07.27
Arrays.sort in Java  (0) 2019.07.23
Collection framework - HashMap  (0) 2019.07.23