1

Getting exception when try get connection on datasource: Cannot create JDBC driver of
class '' for connect URL 'null' Context

web.xml
    </context-param>
    <resource-ref>
        <res-ref-name>jdbc/shop_MYSQL</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

Pom
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
            <version>8.0.20</version>
        </dependency>

       code:
        Context ctx = new InitialContext();
        ds  = (DataSource) ctx.lookup("java:comp/env/jdbc/shop_MYSQL");
        Connection conn = ds.getConnection();

1 Answers1

0

You will need to add the mysql connector jar to Tomcat as it's not included out of the box. Download from here (for the appropriate version of MySQL)

https://dev.mysql.com/downloads/connector/j

Unzip the downloaded zip and copy mysql-connector-java-x.x.xxx.jar to the Tomcat lib folder (not WEB-INF/lib)

Also if you haven't already, define your Datasource as a Resource in Tomcat conf/context.xml

<Resource name="jdbc/shop_MYSQL" auth="Container" type="javax.sql.DataSource"
                   maxActive="100" maxIdle="30" maxWait="10000"
                   username="user" password="password" driverClassName="com.mysql.jdbc.Driver"
                   url="jdbc:mysql://localhost:3306/javatest"/>

Your java code should work as is. However you're not using the resource-ref you defined. Whether you need to or not is debatable - it's for keeping deployer/developer roles separate, see here - but assuming you do, you need an extra line to create the java:/comp/env context and do the lookup on that:

Context ctx = new InitialContext();
Context envCtx  = (Context) ctx.lookup("java:/comp/env");
ds  = (DataSource) envCtx.lookup("jdbc/shop_MYSQL");
Connection conn = ds.getConnection();
ACHC
  • 312
  • 1
  • 2
  • 10