Rich Sala
Rich Sala

Reputation: 93

java.sql.SQLException: No suitable driver found for jdbc

I am attempting to run some queries using JDBC and keep getting this error:

Exception in thread "main" java.lang.IllegalStateException: error
        at com.mycompany.app.App.writer(App.java:195)
        at com.mycompany.app.App.main(App.java:19)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

here is the relevant part of my code:

public class App {
           writer();
}

public static void writer() {
        String url = "jdbc:mysql://localhost:3306/dbname
        String username = "root";
        String password = "password";
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            Statement st = connection.createStatement();
            ResultSet r= st.executeQuery("insert query here");
        } catch (SQLException e) {
            throw new IllegalStateException("error");
        }

    }
}

When I run it through Intellij Idea it works, but I need it to run on a server running Centos.
I have tried running it with this commands:

 javac -cp "filepath/mysql-connector-java-5.1.35-bin.jar" App.java  
 java -cp ".filepath/mysql-connector-java-5.1.35-bin.jar" App

I have tried running it using maven, including

  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
    </dependency>

in pom.xml and still get the same error

I have looked through many articles online (and stack questions) and still can't find the solution.

The server is running CentoOS 6.6 and the database is running locally.

I am using:

java version "1.8.0_45" Java(TM) SE Runtime Environment (build 1.8.0_45-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

Upvotes: 0

Views: 1589

Answers (3)

Sarfaraz Khan
Sarfaraz Khan

Reputation: 2186

You can try loading the driver class using class.forName("qualified name of driver class"). This should resolve the issue if you're not facing the issue of class path with maven. Have a look at this where the index tag was removed from pom and it worked.

Upvotes: 0

Razib
Razib

Reputation: 11163

Alternatively, you may place your mysql-connector-java-5.1.35-bin.jar to the following directory -

JAVA_HOME/jre/lib/ext 

If you place the jar in this directory then you don't have to add it to classpath by using command.

Upvotes: 0

Jesper
Jesper

Reputation: 206796

Entries on the classpath on Unix-like operating systems must be separated by :. Add a : between . (which indicates the current directory) and the path of the jar:

java -cp .:filepath/mysql-connector-java-5.1.35-bin.jar App

Upvotes: 2

Related Questions