javamysqlseleniumdbconnection

Cannot connect Java to MySQL database even after having jar file


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbManager {
    public static Connection conn = null; // mysql
    public static void setMysqlDbConnection() throws SQLException, ClassNotFoundException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("jdbc:mysql://localhost:3306/testdatabase");
            System.out.println("test1");

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase", "root", "Password");
            System.out.println("test2");
            if (!conn.isClosed())
                System.out.println("Successfully connected to MySQL server");

            } catch (Exception e) {
            System.err.println("Cannot connect to database server");
        }
     }
}

Output is:

jdbc:mysql://localhost:3306/testdatabase
test1
Cannot connect to database server

The connection is not working as expected. I have confirmed that the jar installed and connection is working with the username and password on Terminal. Does anyone know what I am doing wrong?


Solution

  • Mentioned serverTimezone explicitly in the code to fix the issue.

    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase?serverTimezone=UTC", "root", "MyPassword");