Search code examples
javamysqljdbcruntime-errordatabase-connection

How can I solve this Java Jdbc connection Error?


I have written a simple Java Jdbc connection program. I have put the MySQL connector jar. I have also put classpath in the environment variable. Still couldn't solve this connection error.

This is my code:

public class check {

    public static void main(String[] args) {

        System.out.println("-------- MySQL JDBC Connection Demo ------------");
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } 
        catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found !!");
            return;
        }
        System.out.println("MySQL JDBC Driver Registered!");
        Connection connection = null;
        try {
            connection = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/company","root","");
            System.out.println("SQL Connection to database established!");

        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            return;
        } finally {
            try
            {
                if(connection != null)
                    connection.close();
                System.out.println("Connection closed !!");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Output:

-------- MySQL JDBC Connection Demo ----------
MySQL JDBC Driver Registered!
Connection Failed! Check output console
Connection closed !!

Solution

  • Replace the following lines

    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
        return;
    }
    

    with

    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
    }
    

    so that you can get the root cause of the issue. Your current code is simply eating that vital information.

    On a side note, remove the following vestigial code:

    try
    {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } 
    catch (ClassNotFoundException e) {
        System.out.println("MySQL JDBC Driver not found !!");
        return;
    }
    

    Class.forName("com.mysql.cj.jdbc.Driver") is not needed since JDBC 4.0.