114

I am trying to create a connection to my database, when I put test my code using the main method, it works seamlessly. However, when trying to access it through Tomcat 7, it fails with error:

No suitable driver found for jdbc:mysql://localhost/dbname. 

I am using pooling. I put in mysql connector (5.1.15), dbcp (1.4) , and pool(1.4.5) libraries in WEB-INF/lib and in .classpath as well. I am using Eclipse IDE. My code for the database driver is:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.tomcat.dbcp.dbcp.ConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.DriverManagerConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolingDriver;
import org.apache.tomcat.dbcp.pool.impl.GenericObjectPool;

public class DatabaseConnector {
    public static String DB_URI = "jdbc:mysql://localhost/dbname";
    public static String DB_USER = "test";
    public static String DB_PASS = "password";

    // Singleton instance
    protected static DatabaseConnector _instance;

    protected String _uri;
    protected String _username;
    protected String _password;

    /**
     * Singleton, so no public constructor
     */
    protected DatabaseConnector(String uri, String username, String password) {
        _uri = uri;
        _username = username;
        _password = password;

        GenericObjectPool connectionPool = new GenericObjectPool(null);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            _uri, _username, _password);
        PoolableConnectionFactory poolableConnectionFactory =
            new PoolableConnectionFactory(connectionFactory, connectionPool,
                                            null, null, false, true);
        PoolingDriver driver = new PoolingDriver();
        driver.registerPool("test", connectionPool);
    }

    /**
     * Returns the singleton instance
     */
    public static DatabaseConnector getInstance() {
        if (_instance == null) {
            _instance = new DatabaseConnector(DB_URI, DB_USER, DB_PASS);
        }
        return _instance;
    }

    /**
     * Returns a connection to the database
     */
    public Connection getConnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return con;
    }
}

Start of my stack trace:

Apr 5, 2011 9:49:14 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Login] in context with path [/Project] 
threw exception
java.lang.RuntimeException: java.sql.SQLException: 
No suitable driver found for jdbc:mysql://localhost/dbname

What is causing this error?

Tamer
  • 1,724
  • 4
  • 16
  • 15
  • 2
    Please note that this is definitely not the correct approach to utilize Tomcat's connection pooling facilities. – BalusC Apr 05 '11 at 19:09
  • 1
    Another thing to look out for is the syntax of the connection url. I had `jdbc:mysql//localhost:3306` instead of `jdbc:mysql://localhost:3306` – Kshitiz Sharma Dec 17 '14 at 05:26

21 Answers21

70

Try putting the driver jar in the server lib folder. ($CATALINA_HOME/lib)

I believe that the connection pool needs to be set up even before the application is instantiated. (At least that's how it works in Jboss)

uncaught_exceptions
  • 21,712
  • 4
  • 41
  • 48
  • This also helped me when I was setting up TeamCity. Copied jar from the Platform Independent zip file into the folder prompted in TeamCity setup and hit refresh drivers button. – Stephen Price Mar 22 '15 at 04:58
  • My enviroment is running in docker, so I added this instruction to Dockerfile: `RUN cd /usr/local/tomcat/lib && wget http://central.maven.org/maven2/org/drizzle/jdbc/drizzle-jdbc/1.3/drizzle-jdbc-1.3.jar && wget http://central.maven.org/maven2/mysql/mysql-connector-java/5.1.27/mysql-connector-java-5.1.27.jar` – julianm Dec 17 '19 at 16:38
  • My tomcat server is running using XAMPP tool so I have added jar file into following path: "C:\xampp\tomcat\lib" and it is working file for me. – Manoj Gupta Jun 05 '21 at 10:21
49

The reason you got this error:

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

Is because you forgot to register your mysql jdbc driver with the java application.

This is what you wrote:

Connection con = null;
try {
    con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
    throw new RuntimeException(e);
}

Should be this:

Connection con = null;
try {
    //registering the jdbc driver here, your string to use 
    //here depends on what driver you are using.
    Class.forName("something.jdbc.driver.YourFubarDriver");   
    con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
    throw new RuntimeException(e);
}

You'll have to read the manual on your specific mysql jdbc driver to find the exact string to place inside the the Class.forName("...") parameter.

Class.forName not required with JDBC v.4

Starting with Java 6, Class.forName("something.jdbc.driver.YourFubarDriver") is not necessary anymore if you use a recent (JDBC v.4) driver. For details read this: http://onjava.com/pub/a/onjava/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
  • 1
    Prior to the release of the JDBC 4.0 specification, the client application needed to load the Driver class via the command Class.forName("..."). I even checked META-INF/services/java.sql.Driver file. In my case application runs fine in jetty server (via maven or stand alone), but when I try to run it in other servers (I tested in tomcat and glassfish) I get above error. I even tried to copy mysql-connector-java-5.1.18.jar inside apache-tomcat-7.0.23/lib, so what might be the cause of it not running in these servers. – Pramod Dec 14 '11 at 07:20
  • 6
    I've found that with Tomcat 7 and Java 7 it is once again necessary to execute Class.forName("something.jdbc.driver.YourFubarDriver"); At least this solved this problem for me on one deployment. The same .war worked fine on Tomcat 5.5 with Java 6, but threw the no suitable driver exception on 7/7. – Brad Whitaker May 03 '12 at 23:16
  • 3
    No, starting with Java 6, Class.forName("something.jdbc.driver.YourFubarDriver") is not necessary anymore **if** you use a recent (JDBC v.4) driver. Probably with Tomcat 7 you where using an older driver than with Tomcat 5.5. See Javadoc of DriverManager for details. – Pino Sep 13 '12 at 13:49
  • 3
    You should not need them. However, it is highly dependent on the driver version/OS version/Tomcat version/Java version. Even "recent" driver and JDK combinations may fail. To be on the safe side, you need to use Class.forName – Lorenzo Dematté Apr 15 '14 at 07:58
  • 13
    According to http://tomcat.apache.org/tomcat-8.0-doc/jndi-datasource-examples-howto.html#DriverManager,_the_service_provider_mechanism_and_memory_leaks "web applications that have database drivers in their WEB-INF/lib directory cannot rely on the service provider mechanism and should register the drivers explicitly." – Shannon Jan 09 '15 at 21:52
  • Technically it is not required with JDBC 4+... but the project I am working on requires it to load the Postgres JDBC. It was working fine in a small standalone project, but for some reason the Class.forName(...) was needed in the main web project. Weird stuff. – DeveloperDemetri Feb 19 '16 at 20:17
  • 2
    I'm confused, why was it _ever_ necessary to call `Class.forName`? Shouldn't this class be on the classpath? Why do we need to "load" a class manually? I've never needed to manually load a class, what's special about this one? – DavidS Jun 09 '16 at 23:21
  • @DavidS Loading a JDBC driver class causes the class to register itself at the `DriverManager` as required by the JDBC specification, see https://stackoverflow.com/q/32922459 and https://stackoverflow.com/q/5484227. – Martin May 13 '18 at 06:03
42

I had the same problem using Tomcat7 with mysql-connector-java-5.1.26 that I put in both my $CATALINA_HOME/lib and WEB-INF/lib, just in case. But it wouldn't find it until I used either one of these two statements before getting the connection:

DriverManager.registerDriver(new com.mysql.jdbc.Driver ());

OR

Class.forName("com.mysql.jdbc.Driver");

I then followed up with removing mysql-connector-java-5.1.26 from $CATALINA_HOME/lib and the connection still works.

ybenjira
  • 549
  • 4
  • 4
  • You don't need either statements, for me it worked by just moving the connector to WEB-INF/lib. – Vlad Schnakovszki Dec 03 '13 at 11:25
  • 3
    You *should* not need them. However, it is highly dependent on the driver version/OS version/Tomcat version/Java version. Even "recent" driver and JDK combinations may fail. To be on the safe side, you need to use Class.forName – Lorenzo Dematté Apr 15 '14 at 07:57
  • 1
    "should not need" and reality are different =) Have to register driver when running both under Tomcat 7 and 8. – Alfishe Jul 02 '14 at 13:07
  • 2
    Text copied from this answer: http://stackoverflow.com/a/5484287/2479087 ; Never call DriverManager.registerDriver() method manually. The JDBC spec requires a driver to register itself when the class is loaded, and the class is loaded via Class.forName(). In JDBC 4 the drivers are able to be loaded automatically just by being on the class path. – Max Jul 10 '14 at 15:47
  • I think, its good practice to register driver before performing operations.. – peaceUser Dec 21 '16 at 05:07
  • This helps me. Thanks a lot! – iscariot Aug 08 '17 at 17:47
  • Tomcat 8/JDK 1.7: After forced unregistration, Class.forName() doesn't work, registerDriver() does. – access_granted Sep 21 '18 at 20:52
7

When running tomcat out of eclipse it won't pick the lib set in CATALINA_HOME/lib, there are two ways to fix it. Double click on Tomcat server in eclipse servers view, it will open the tomcat plugin config, then either:

  1. Click on "Open Launch Config" > Classpath tab set the mysql connector/j jar location. or
  2. Server Location > select option which says "Use Tomcat installation (take control of Tomcat installation)"
DaSourcerer
  • 6,288
  • 5
  • 32
  • 55
bjethwan
  • 97
  • 1
  • 3
5

I had the mysql jdbc library in both $CATALINA_HOME/lib and WEB-INF/lib, still i got this error . I needed Class.forName("com.mysql.jdbc.Driver"); to make it work.

nondescript
  • 1,476
  • 1
  • 13
  • 16
5

add the artifact from maven.

 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
 </dependency>
Tunde Pizzle
  • 787
  • 1
  • 9
  • 18
4

I'm running Tomcat 7 in Eclipse with Java 7 and using the jdbc driver for MSSQL sqljdbc4.jar.

When running the code outside of tomcat, from a standalone java app, this worked just fine:

        connection = DriverManager.getConnection(conString, user, pw);

However, when I tried to run the same code inside of Tomcat 7, I found that I could only get it work by first registering the driver, changing the above to this:

        DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
        connection = DriverManager.getConnection(conString, user, pw);
nick
  • 41
  • 1
4

Use:

try {

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    System.out.println("Registro exitoso");

} catch (Exception e) {

    System.out.println(e.toString());

}

DriverManager.getConnection(..
Max
  • 1,325
  • 9
  • 20
4

Bro, you can also write code as below:

import java.sql.*;
import java.io.*;
public class InsertDatabase {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try
    {  
        Class.forName("com.mysql.jdbc.Driver");  
        Connection con=DriverManager.getConnection(  
        "jdbc:mysql://localhost:3306/Maulik","root","root");  

        Statement stmt=con.createStatement();  
        ResultSet rs=stmt.executeQuery("select * from Employee");  
        while(rs.next())  
        System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
        con.close();
    }

    catch(Exception e)
    {
        System.out.println(e);
    }

        }  

}
Maulik
  • 349
  • 4
  • 19
3

I had the same problem, all you need to do is define classpath environment variable for tomcat, you can do it by adding a file, in my case C:\apache-tomcat-7.0.30\bin\setenv.bat, containing:

set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\lib\mysql-connector-java-5.1.14-bin.jar"

then code, in my case:

Class.forName("com.mysql.jdbc.Driver").newInstance(); 
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "root", "");

works fine.

Aliaksandr Belik
  • 12,725
  • 6
  • 64
  • 90
test30
  • 3,496
  • 34
  • 26
  • This helped me alot, but in my case I had to change from `DriverManager.getConnection("jdbc:mysql://localhost:3306;user=username;password=password;database=databasename")` to `DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","user","password")` – desw Jun 29 '15 at 07:21
  • This solved the issue for me – Jones G Feb 25 '18 at 01:45
3

I also had the same problem some time before, but I solved that issue.

There may be different reasons for this exception. And one of them may be that the jar you are adding to your lib folder may be old.

Try to find out the latest mysql-connector-jar version and add that to your classpath. It may solve your issue. Mine was solved like that.

j0k
  • 22,600
  • 28
  • 79
  • 90
1

if you are using netbeans you must add Mysql JDBC driver in the library list of the project, in the properties of your project

Gapchoos
  • 1,422
  • 5
  • 20
  • 40
1

Most of time it happen because two mysql-connector-java-3.0.14-production-bin.jar file. One in lib folder of tomcat and another in classpath of the project.

Just try to remove mysql-connector-java-3.0.14-production-bin.jar from lib folder.

This way it is working for me.

RKP
  • 99
  • 6
1

From what i have observed there might be two reasons for this Exception to occur: (1)Your Driver name is not spelled Correctly. (2)Driver hasn't been Associated Properly with the Java Project Steps to follow in Eclipse: (1)Create a new Java Project. (2)copy The connector Jar file (3)Right Click on the Java project and paste it there. (4)Right click on the Java project -> Properties ->Java Build Path - >libraries-> Add Jar ->choose ur project(select the jar file from dropdown) and click ok.

Abhishek J
  • 24
  • 1
1

The solution is straightforward.

Make sure that the database connector can be reached by your classpath when running (not compiling) the program, e.g.:

java -classpath .;c:\path\to\mysql-connector-java-5.1.39.jar YourMainClass 

Also, if you're using an old version of Java (pre JDBC 4.0), before you do DriverManager.getConnection this line is required:

Class.forName("your.jdbc.driver.TheDriver"); // this line is not needed for modern Java
Pacerier
  • 86,231
  • 106
  • 366
  • 634
0

When developing using Ubuntu (Xubuntu 12.04.1) I 'HAD' to do the following:

Using

Eclipse Juno (downloaded, not installed via the software centre), Tomcat 7 (downloaded in a custom user directory) also added as a Server in Eclipse, Dynamic Web Project with a 3.0 Servlet, MySQL Server on localhost configured and tested with user and password (make sure to test) MySQL connector driver 5.1.24 jar,

I 'HAD', and I repeat 'HAD', to us the Class.Load("com.mysql.jdbc.Driver") statement along with adding the connector driver.jar to be in the web project lib folder for it to work in this situation.

IMPORTANT!!: after you copy the driver.jar to the lib make sure you refresh your project in Eclipse before running the servlet via Tomcat.

I did try adding the connector driver jar file via the Build Path with and without ClassLoad but it did not work!

Hope this helps anyone starting development with this specific situation: the Java community provides a 'LOT' of documentation but there are so many variables its hard to cover all of them and it makes things very hard on the new guy.

I think if someone could explain why Class.Load is required here (in this situation) it would be beneficial.

Enjoy

0

Since no one gave this answer, I would also like to add that, you can just add the jdbc driver file(mysql-connector-java-5.1.27-bin.jar in my case) to the lib folder of your server(Tomcat in my case). Restart the server and it should work.

Susie
  • 5,038
  • 10
  • 53
  • 74
  • 1
    Not really a good advice especially if you have multiple applications using different driver versions – Alfishe Jul 02 '14 at 13:08
0
  1. Put mysql-connector-java-5.0.8-bin.jar in $CATALINA_HOME/lib

  2. Check for typo in connection url, example
    "jdbc:mysql://localhost:3306/report" ('report' here is the db name)

  3. Make sure to use machine name(example : localhost instead of ip address(127.0.0.1))
Bruce
  • 793
  • 8
  • 17
0

Add the driver class to the bootstrapclasspath. The problem is in java.sql.DriverManager that doesn't see the drivers loaded by ClassLoaders other than bootstrap ClassLoader.

arathim
  • 36
  • 5
0

From other stackoverflow thread:

"Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter's classpath. If you don't - download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter's /lib folder. JMeter restart will be required to pick the library up"

Please be sure that .jar file is added directly to the lib folder.

-2

You can stick the jar in the path of run time of jboss like this:

C:\User\user\workspace\jboss-as-web-7.0.0.Final\standalone\deployments\MYapplicationEAR.ear\test.war\WEB-INF\lib ca marche 100%

ChrisF
  • 134,786
  • 31
  • 255
  • 325