-1

Here is my code:

import java.sql.*; import com.mysql.jdbc.Driver; public class Main { public void connect() { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql//localhost:3306/mydb", "dev", "pass"); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) try { con.close(); } catch(Exception e) {} } } public static void main(String[] args) { Main m = new Main(); m.connect(); } } 

I have imported mysql-connector-java-5.1.39.jar as a library in IntelliJ and as you can see the driver is imported in the code.

But I get:

java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/mydb 

I have looked at countless stack overflow questions and I can't figure out what more it needs to at least attempt a connection. I have a local SQL server running, and I've double checked the port and database name.

Any ideas would be appreciated, thanks.

EDIT: this is not a duplicate. The solution to the other question that someone flagged is not relevant here. I had already added the jar as a library for the project, as described in the other question. Also, the crash doesn't happen on the "Class.forName" part, it crashes on the subsequent line.

3

3 Answers 3

4

You are missing a colon character in the connection URI.

"jdbc:mysql//localhost:3306/mydb" 

should be

"jdbc:mysql://localhost:3306/mydb" 

See Connecting to MySQL Using the JDBC DriverManager Interface.

The missing colon means that the driver manager will attempt to look for a driver provider called "mysql//localhost" rather than "mysql". Of course, no such provider exists.


The Class.forName call in your code is not necessary. But the fact that the call succeeding is a strong clue that the problem is NOT that the driver class is missing. It should cause the reader to look for other reasons why DriverManager couldn't find the driver.

Sign up to request clarification or add additional context in comments.

Comments

1
jdbc:mysql//localhost:3306/mydb 

You are missing a colon after mysql.

NB the Class.forName()line hasn't been necessary for ten years.

Comments

0

The JDBC connection string for MySQL has been well explained here in the MySQL documentation. Based on that, the mistake that you've done here is a simple miss of colon after the database type, mysql

You're connection string (without the credentials, though) is going to change from this:

"jdbc:mysql//localhost:3306/mydb" 

To this:

"jdbc:mysql://localhost:3306/mydb" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.