How to fix: “No suitable driver found for jdbc:mysql://localhost/dbname” error when using pools? [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-16 19:57:39

问题


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?


回答1:


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)




回答2:


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




回答3:


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.




回答4:


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



回答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.




回答6:


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.




回答7:


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

        }  

}



回答8:


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



回答9:


add the artifact from maven.

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



回答10:


Use:

try {

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

} catch (Exception e) {

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

}

DriverManager.getConnection(..



回答11:


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




回答12:


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.




回答13:


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.




回答14:


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.




回答15:


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



回答16:


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




回答17:


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.




回答18:


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



回答19:


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.




回答20:


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.




回答21:


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%



来源:https://stackoverflow.com/questions/5556664/how-to-fix-no-suitable-driver-found-for-jdbcmysql-localhost-dbname-error-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!