如何修复:“使用池时没有找到适合jdbc:mysql:// localhost / dbname的驱动程序”错误?

参见英文答案 > The infamous java.sql.SQLException: No suitable driver found                                    13个
我正在尝试创建与我的数据库的连接,当我使用main方法测试我的代码时,它可以无缝地工作.但是,当尝试通过Tomcat 7访问它时,它会失败并显示错误:

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

我正在使用汇集.我在WEB-INF / lib和.classpath中放入了mysql连接器(5.1.15),dbcp(1.4)和pool(1.4.5)库.我正在使用Eclipse IDE.我的数据库驱动程序代码是:

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

我的堆栈跟踪开始:

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

导致此错误的原因是什么?

最佳答案
尝试将驱动程序jar放在服务器lib文件夹中. ($CATALINA_HOME / lib中)

我相信甚至在实例化应用程序之前就需要设置连接池. (至少这是它在Jboss中的工作方式)

转载注明原文:如何修复:“使用池时没有找到适合jdbc:mysql:// localhost / dbname的驱动程序”错误? - 代码日志