How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

MysqlJdbcTomcat7Apache Commons-Dbcp

Mysql Problem Overview


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?

Mysql Solutions


Solution 1 - Mysql

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)

Solution 2 - Mysql

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

Solution 3 - Mysql

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.

Solution 4 - Mysql

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)"

Solution 5 - Mysql

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.

Solution 6 - Mysql

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);
	}
		  
		}  
		
}

Solution 7 - Mysql

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.

Solution 8 - Mysql

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.

Solution 9 - Mysql

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);

Solution 10 - Mysql

add the artifact from maven.

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

Solution 11 - Mysql

Use:

try {

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

} catch (Exception e) {

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

}

DriverManager.getConnection(..

Solution 12 - Mysql

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

Solution 13 - Mysql

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.

Solution 14 - Mysql

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.

Solution 15 - Mysql

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

Solution 16 - Mysql

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

Solution 17 - Mysql

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.

Solution 18 - Mysql

  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))

Solution 19 - Mysql

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.

Solution 20 - Mysql

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.

Solution 21 - Mysql

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%

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTamerView Question on Stackoverflow
Solution 1 - Mysqluncaught_exceptionsView Answer on Stackoverflow
Solution 2 - MysqlEric LeschinskiView Answer on Stackoverflow
Solution 3 - MysqlybenjiraView Answer on Stackoverflow
Solution 4 - MysqlbjethwanView Answer on Stackoverflow
Solution 5 - MysqlnondescriptView Answer on Stackoverflow
Solution 6 - MysqlMaulikView Answer on Stackoverflow
Solution 7 - Mysqltest30View Answer on Stackoverflow
Solution 8 - MysqlAnkit PawarView Answer on Stackoverflow
Solution 9 - MysqlnickView Answer on Stackoverflow
Solution 10 - MysqlTunde PizzleView Answer on Stackoverflow
Solution 11 - MysqlJoan Payano CamachoView Answer on Stackoverflow
Solution 12 - MysqlSérgio SilvaView Answer on Stackoverflow
Solution 13 - MysqlRKPView Answer on Stackoverflow
Solution 14 - MysqlAbhishek JView Answer on Stackoverflow
Solution 15 - MysqlPacerierView Answer on Stackoverflow
Solution 16 - MysqlMtlMikeView Answer on Stackoverflow
Solution 17 - MysqlSusieView Answer on Stackoverflow
Solution 18 - MysqlBruceView Answer on Stackoverflow
Solution 19 - MysqlarathimView Answer on Stackoverflow
Solution 20 - Mysqladrian filipescuView Answer on Stackoverflow
Solution 21 - Mysqluser4983785View Answer on Stackoverflow