Question

I don't know what is wrong with this code? It throws a SQL Exception: No suitable driver found for jdbc:mysql://localhost:3306/test.

But I have included the jar file mysql-connector-java-5.0.8-bin.jar

I have attempted to get a connection through a connection pool via datasource.

I hope someone could help me to sort out this issue.

Please ignore if there are any logging errors I want someone to resolve the connection error that has been highlighted above

import java.sql.*;

import javax.annotation.Resource;
import javax.naming.*;
import javax.sql.*;

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.PoolingDataSource;
import org.apache.tomcat.dbcp.pool.impl.GenericObjectPool;

public class GetConnection {
    /** Uses JNDI and Datasource (preferred style). */

    @Resource(name = "jdbc/test")
    DataSource ds;
    static final String DRIVER = "com.mysql.jdbc.Driver";
    static final String DATASOURCE_CONTEXT = "java:comp/env/jdbc/test";
    private GenericObjectPool connectionPool = null;
    public static final String URL = "jdbc:mysql://localhost:3306/test";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "secret_password";

    public GetConnection() {
        System.out.println("enteredin to the new get connection");
        /*try {
            Context context = new InitialContext();
            ds = (DataSource) context.lookup(DATASOURCE_CONTEXT);
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        try {
            ds = setUp();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public DataSource setUp() throws Exception {
        Class.forName(GetConnection.DRIVER).newInstance();
        connectionPool = new GenericObjectPool();
        connectionPool.setMaxActive(10);
        ConnectionFactory cf = new DriverManagerConnectionFactory(
                GetConnection.URL, GetConnection.USERNAME,
                GetConnection.PASSWORD);
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf,
                connectionPool, null, null, false, true);
        return new PoolingDataSource(connectionPool);
    }

    public GenericObjectPool getConnectionPool() {
        return connectionPool;
    }

    /**
     * Sets up the dataSource for the connection
     */

    /**
     * returns the connection object from the datasource
     * 
     * @return the connection object
     */
    public Connection getJNDIConnection() {
        System.out.println("entered in to the get jndi connection");
                    System.out.println(ds);
                    System.out.println("checking the ds value");
        Connection result = null;
        try {
            System.out.println("Inside try");
            /*Context initialContext = new InitialContext();
            this.ds = (DataSource) initialContext.lookup(DATASOURCE_CONTEXT);*/
            if (ds != null) {
                result = this.ds.getConnection();
                System.out.println("connection done");
            } else {
                log("Failed to lookup datasource.");
                System.out.println("connection not done");
            }
        } /*catch (NamingException ex) {
            ex.printStackTrace();
            System.out.println("naming excepti9on");
            log("Cannot get connection: " + ex);
        } */catch (SQLException ex) {
            ex.printStackTrace();
            System.out.println("sqlexception");
            log("Cannot get connection: " + ex);
        }
        return result;
    }

    private static void log(Object aObject) {
        System.out.println(aObject);
    }
}

The context file for the project is as shown below

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource" username="root" password="secret_password" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/test;create=true" />
</Context>

The stack trace is below

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at org.apache.tomcat.dbcp.dbcp.DriverManagerConnectionFactory.createConnection(DriverManagerConnectionFactory.java:75)
    at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
    at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1158)
    at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
    at com.new.connection.GetConnection.getJNDIConnection(GetConnection.java:81)
    at com.new.daoclass.CreateUserAgreement.createUser(CreateUserAgreement.java:17)
    at com.new.bean.useragreement.UserAgreementBean.createagreement(UserAgreementBean.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
    at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
    at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:88)
    at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:100)
    at javax.faces.component.UICommand.broadcast(UICommand.java:120)
    at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:937)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:271)
    at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1249)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:675)
    at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:34)
    at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171)
    at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Was it helpful?

Solution

Please put it in the ${CATALINA_HOME}/lib directory and restart the server. This is because you are trying to access the connection from pool which should be created by tomcat during configuring the datasource. so, it needs the mysql-driver.jar to configure the datasource. so, provide it the jar by placing it in tomcat/lib. You can download from this link.

OTHER TIPS

You're trying to access a database connection from a pool that is supposed to be created by Tomcat. So Tomcat needs to have the JDBC driver in its own classpath. Add the JDBC driver to the tomcat/lib directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top