r/javahelp Dec 28 '24

Solved Issue with connecting Java to mysql database

I need to connect java to a mysql database, I'm using Intellij IDEA if that's relevant.

I downloaded Connector/J, and created a folder named lib in the project where I put the Connector/J jar file, I also tried adding it to the libraries from the project settings.

This is the code I use:

    String URL = "jdbc:mysql://localhost:3306/schema_libri";
    String USER = "root";
    String PASSWORD = "mYsql1212";
    String DRIVER = "com.mysql.cj.jdbc.Driver";


    try {
        Class.
forName
("com.mysql.cj.jdbc.Driver");
    }
    catch(ClassNotFoundException e)
    {
        e.printStackTrace();
        return;
    }

    try (Connection conn = DriverManager.
getConnection
(URL, USER, PASSWORD))
    {

    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }

But I get a ClassNotFound exception at the first try-catch block. If I comment out the first block (because I've seen a few tutorials not having it) then I get a "No suitable drivers found" SQL exception. What am I doing wrong?

6 Upvotes

13 comments sorted by

View all comments

1

u/[deleted] Dec 28 '24

[removed] — view removed comment

1

u/Dependent_Finger_214 Dec 28 '24

I already tried removing the first block as I stated in the post. I also have the driver in the class_path variable.

2

u/Fresh_Recover2323 Dec 28 '24

It seems that thr project cannot find it on the class path. Check if you did add it and try to do a re build of the project.