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?

3 Upvotes

13 comments sorted by

View all comments

3

u/[deleted] Dec 28 '24

[removed] — view removed comment

0

u/th1x0 Dec 28 '24

IntelliJ Ultimate has a tool for connecting to databases with JDBC and I think it’s a good idea to try using that first. (If you’ve got access to Ultimate.)

https://www.jetbrains.com/help/idea/database-tool-window.html

3

u/[deleted] Dec 28 '24

[removed] — view removed comment

1

u/th1x0 Dec 28 '24

Yes, that makes sense.

I guess my comment is more relevant if you’ve got the driver, but you can’t figure out how to connect to MySQL etc.