Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Using MySQL with Java

Hello,

I'm trying to create a connection to a MySQL database in java and am having issues with the JDBC driver. Here is my code to test the connection:

<code> import java.sql.*; import java.sql.DriverManager;

public class test {

public static void main(String[] args) {
    final String DB_URL = "jdbc:mysql://localhost:3306";

    try {

        Connection conn = DriverManager.getConnection(DB_URL, "user", "password");
        System.out.println("Connection created");

        conn.close();
        System.out.println("Connection closed.");

    }
    catch(Exception ex) {
        System.out.println("ERROR: " + ex.getMessage());
    }
}

} </code>

I keep getting the error: "No suitable driver found for jdbc:mysql://localhost:3306". I'm having trouble setting the classpath with the driver. If anyone could help me I would appreciate it.

Thanks, Jacob

1 Answer

You need to add the .jar file for the mysql-connector-java. There might be a way to import from your IDE or you can just get it from mysql.com and copy the file to your lib directory. I also have this line before my .getConnection, it seems to work without it but maybe its required if you use more than 1 type of database in your app.

Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(... );