JDBC data source not working when project deployed on tomcat - java

I have developed a servlet which calls a MariaDB database through a JDNI datasource. This works fine when I run the web project within eclipse on a tomcat server run within eclipse.
However, when I deploy the project on a tomcat server outside eclipse, using a WAR file, the same servlet does not work. For testing purposes, the project also contains another servlet that connect directly (i.e. not using the JDNI datasource) to the same mariaDB and it works fine even when deployed to tomcat server outside eclipse.
I am running out of ideas concerning what could possibly be wrong and would greatly appreciate if someone could shed some light.
Configuration information:
OS : macOS High Sierra
tomcat version : 8.5
eclipse : Neon.2., release 4.6.2
Java : 8
MariaDB driver : mariadb-java-client-2.2.0
Outiside eclipse, The driver is in two locations:
/tomcat-folder/lib
/tomcat-folder/webapps/my-app/WEB-INF/lib (from the WAR file)
I have added the following resource reference to the application web.xml file:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MYDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I have added the following resource to /tomcat-folder/contf/context.xml:
<Resource name="jdbc/MYDB” auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="" driverClassName="org.mariadb.jdbc.Driver"
url="jdbc:mariadb//localhost:3306/MYDB”/>
The error I get is :
java.sql.SQLException: Cannot create JDBC driver of class 'org.mariadb.jdbc.Driver' for connect URL 'jdbc:mariadb//localhost:3306/MYDB'
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2167)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2037)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
at DBConfigTest.getConnection(DBConfigTest.java:123)
at DBConfigTest.doGet(DBConfigTest.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: No suitable driver
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2158)
... 28 more
java.lang.NullPointerException
at DBConfigTest.doGet(DBConfigTest.java:61)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
the servlet code is as follows:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConfigTest extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// JDBC driver name and database URL
// static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
// static final String DB_URL="jdbc:mariadb://localhost/MYDB"+"?user=root&password=";
// Database credentials
// static final String USER = "root";
// static final String PASS = "";
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
// Execute SQL query
//Statement stmt=null;
//Connection conn=null;
Connection connection=null;
PreparedStatement statement=null;
try {
// Register JDBC driver
//Class.forName("org.mariadb.jdbc.Driver");
// Open a connection
//conn = DriverManager.getConnection("jdbc:mariadb://localhost/MYDB"+"?user=root&password=");
connection = getConnection();
String sql = "SELECT * FROM ingredient";
statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
// Execute SQL query
/*stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM ingredient";
ResultSet rs = stmt.executeQuery(sql);*/
// Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("ingredient_id");
String code = rs.getString("ingredient_code");
String description = rs.getString("ingredient_description");
//Display values
out.println("ID: " + id + "<br>");
out.println(", Code: " + code + "<br>");
out.println(", Description: " + description + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
statement.close();
connection.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(statement!=null)
statement.close();
} catch(SQLException se2) {
} // nothing we can do
try {
if(connection!=null)
connection.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
}
private Connection getConnection() {
Connection connection = null;
try {
/*InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("jdbc/MYDB");
connection = dataSource.getConnection();*/
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/MYDB");
connection = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}

The url in the example below should be url="jdbc:mariadb://localhost:3306/MYDB”. A colon (:) in the JDBC URL, after mariadb and before //, was missing.
<Resource name="jdbc/MYDB” auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="" driverClassName="org.mariadb.jdbc.Driver"
url="jdbc:mariadb//localhost:3306/MYDB”/>

Related

java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null' in IntelliJ web application

I am trying to build a small web application using servlets on IntelliJ. I am trying to connect MySQL DB with the application using JDBC.
I have the required maven dependencies, checked my context.xml file.
I manually tried connecting the MySQL DB using the GUI on IntelliJ which is getting connected successfully.
<Context>
<Resource name="jdbc/student_tracker"
auth="Container" type="javax.sql.DataSource"
maxActive="20" maxIdle="5" maxWait="10000"
username="webstudent" password="webstudent"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/web_student_tracker"/>
</Context>
Here is the Servlet
#WebServlet(name = "TestServlet", value = "/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Define datasource/connection pool for Resource Injection
#Resource(name="jdbc/student_tracker")
private DataSource dataSource;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Step 1: Set up the printwriter
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
// Step 2: Get a connection to the database
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
myConn = dataSource.getConnection();
// Step 3: Create a SQL statements
String sql = "select * from student";
myStmt = myConn.createStatement();
// Step 4: Execute SQL query
myRs = myStmt.executeQuery(sql);
// Step 5: Process the result set
while (myRs.next()) {
String email = myRs.getString("email");
out.println(email);
}
}
catch (Exception exc) {
exc.printStackTrace();
}
}
The error
java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp2.DriverFactory.createDriver(DriverFactory.java:74)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:472)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:538)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:744)
at com.application.student_tracker.TestServlet.doGet(TestServlet.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:196)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:624)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1650)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(DriverManager.java:315)
at org.apache.tomcat.dbcp.dbcp2.DriverFactory.createDriver(DriverFactory.java:59)
If you are using JNDI for DataSource you have to have the JDBC driver in $CATALINA_HOME/lib., copy the mysql-connector to $CATALINA_HOME/lib
Also remove it from your WEB-INF/lib
REF: JNDI Datasource HOW-TO

Null Pointer Exception Running JDBC Tomcat Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a SQL database which we managed to get connected using the proper drivers. Firstly here's the code
package com.Derp.test.blah;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.io.PrintWriter;
public class DBConnect {
String databaseURL;
String user;
String password;
public DBConnect(String inurl, String inuser, String inpass) {
databaseURL = inurl;
user = inuser;
password = inpass;
}
#SuppressWarnings("null")
public List<String> dbConnector() throws ClassNotFoundException {
System.out.println("dburl: "+databaseURL);
System.out.println("user: "+user);
System.out.println("pass: "+password);
List<String> imgPaths = null;
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(databaseURL, "service_manager", "watermelon");
if (conn != null) {
System.out.println("Connected to the database");
Statement s = conn.createStatement();
//Count the amount of users in the Accounts table with the user name of the query
System.out.println("Before executeQuery");
ResultSet rs = s.executeQuery("SELECT * FROM testable");
while(rs.next()){
System.out.println(rs.getString("imgpath"));
imgPaths.add(rs.getString("imgpath"));
}
System.out.println("Size of Images: " + imgPaths.size());
//return imgPaths;
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return imgPaths;
Ignore how horrible some parts of this code is please. In the while loop
System.out.println(rs.getString("imgpath"));
Is printing out results to the console that are in the SQL database, however I am unable to add the results to the imgPaths String List, and am getting the following error.
Jan 30, 2019 10:20:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.Derp.test.blah.TestServlet] in context with path [/BlahTest] threw exception
java.lang.NullPointerException
at com.Derp.test.TestBlah.DBConnect.dbConnector(DBConnect.java:39)
at com.Derp.test.TestBlah.TestServlet.doGet(TestServlet.java:140)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Null pointer exception... Any help would be greatly appreciated.
Your imgPaths variable is initialized to null. Change the initialization to a list object then it would allow you to add items.

Cannot create JDBC driver of class '' for connect URL 'jdbc:mysql://localhost:3306/web13?useSSL=false&serverTimezone=UTC'

I created a properties file
url=jdbc:mysql://localhost:3306/web13?useSSL=false&serverTimezone=UTC
username=root
password=root
and I created a connection pool
private static DataSource dataSource;
static {
try {
//load properties file
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
//load input stream
Properties props = new Properties();
props.load(is);
//create data source
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
Then I got the problem. I searched some anwsers, they said driver needs to be registered like Class.forName(com.mysql.jdbc.Driver). But my version of driver seems to be able to register by itself, so this solution can not work.
Error:
Oct 02, 2018 9:46:09 AM org.apache.catalina.core.StandardContext
reload INFO: Reloading Context with name [/WEB13] is completed
java.sql.SQLException: Cannot create JDBC driver of class '' for
connect URL
'jdbc:mysql://localhost:3306/web13?useSSL=false&serverTimezone=UTC'
at
org.apache.commons.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2224)
at
org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2104)
at
org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1563)
at
org.apache.commons.dbutils.AbstractQueryRunner.prepareConnection(AbstractQueryRunner.java:319)
at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:327)
at com.itheima.login.LoginServlet.doGet(LoginServlet.java:36) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748) Caused by:
java.sql.SQLException: No suitable driver at
java.sql.DriverManager.getDriver(DriverManager.java:315) at
org.apache.commons.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2209)
... 29 more
Your properties file is missing a property, which means the DBCP is not able to create/initialize the driver.
You need to add
driverClassName = org.mysql.jdbc.Driver
#Ziyan Zhu,
You have added wrong url in db.properties:
url in db properties be like jdbc:mysql://localhost:3306/web13 where web13 is your database name.
In addition you are missing some method in your connection pool as described over here
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBCPUtils {
private static DataSource dataSource;
static {
try {
// 1.Load the properties file input stream
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
// 2.Load the input stream
Properties props = new Properties();
props.load(is);
// 3.create data source
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
i just had the same problem, but i was working with glassfish. if there is anyone in the future who has this problem attempting establishing a database connection in glassfish server, the solutions is to add java mysql connector to glassfish server then your problem is solved.
go to .../glassfish-installation-folder/Glassfish[your-version]/glassfish/lib/here-paste-your-mysql-connector-driver.jar
it's my pleasure. :)

no suitable driver exception in connection pooling

I am trying to implement connection pooling using servlet. I know there are lots of similar questions has been asked but none is able to help.
Here is exception :
java.sql.SQLException: Cannot create JDBC driver of class for connect URL null at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2160)
at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2032)
at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1532)
at
connection.CityInfoServlet.showCityInformation(CityInfoServlet.java:104)
at connection.CityInfoServlet.doGet(CityInfoServlet.java:76) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source) Caused by:
java.sql.SQLException: No suitable driver at
java.sql.DriverManager.getDriver(Unknown Source) at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2144)
... 27 more
I don't know why this exception show :
Caused by: java.sql.SQLException: No suitable driver.
I added jar file in WEB-INF/lib folder.
Here is my Servlet Code :
package connection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
#WebServlet("/CityInfoServlet")
public class CityInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
DataSource dataSource = null;
public void init( ServletConfig config ) {
try{
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/worldDB");
}
catch( Exception exe )
{
exe.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "City Information From Mysql Database";
out.print("<html><body bgcolor=\"#f0f0f0\">");
out.print("<h1 align=\"center\">" + title + "</h1>\n");
showCityInformation(out);
out.print("</body></html>");
}
private void showCityInformation( PrintWriter out )
{
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
String sql = "select * from city limit ?";
connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 10);
ResultSet rs = preparedStatement.executeQuery();
while( rs.next() )
{
int id = rs.getInt(1);
String name = rs.getString(2);
String countryCode = rs.getString(3);
String district = rs.getString(4);
int population = rs.getInt(5);
out.print("ID: " + id + "<br>");
out.print("Name: " + name+ "<br>");
out.print("CountryCode: " + countryCode+ "<br>");
out.print("District: " + district+ "<br>");
out.println("Population: " + population+ "<br>");
out.println("--------------------------------------"+ "<br>");
}
rs.close();
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
try {
if( preparedStatement != null ) {
preparedStatement.close();
}
}
catch( SQLException sqlException ){
sqlException.printStackTrace();
}
try
{
if( connection != null )
{
connection.close();
}
}
catch( SQLException sqlException )
{
sqlException.printStackTrace();
}
}
}
}
This is context.xml file
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/worldDB" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="12345" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/world"/>
</Context>
Cannot create JDBC driver of class for connect URL null
The URL for the connection isn't set, so the JDBC libraries can't determine what driver to load.
I think that..
1 - you have to copy suitable driver to Server/lib folder
2 - If you have to created DataSource Connection context.xml on your project META-INF then modify
3 - WEB.xml of you project like this (add this)
<resource-ref>
<description>MySQLDatasource</description>
<res-ref-name>jdbc/worldDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Then you can run this app http://localhost:8080/app_name - ok
but if you want to call this app from http://localhost:8080
then you have to
1 - add Context tag to your Server/conf/server.xml file
2 - add this line to your Server/conf/context.xml
<Resource name="jdbc/worldDB" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="12345" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/world"/>
3 - restart server
then it will find this connection from Server context.

Connect Servlet to MySQL database in eclipse [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 6 years ago.
I successfully connected database with simple java program using JDBC but when I am trying to connect database with Servlet, it gives me following errors and exceptions:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8888/ebookshop
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at QueryServlet.doGet(QueryServlet.java:35)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
All severs running well and also I already added servlet and connecter API's in my library.
For more Information these are my html and servlet files are:
html file
<html>
<head><title>Yet Another Bookshop</title></head>
<body>
<h2>Yet Another Bookshop</h2>
<form method="get" action="http://localhost:9999/Sixth/query">
<b>Choose an author:</b>
<input type="checkbox" name="author" value="Tan Ah Teck">Ah Teck
<input type="checkbox" name="author" value="Mohammad Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Search">
</form>
</body>
</html>
My servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDK 6 and above only
// The doGet() runs once per HTTP GET request to this servlet.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
try {
// Step 1: Allocate a database Connection object
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
// Step 3: Execute a SQL SELECT query
String sqlStr = "select * from books where author = "
+ "'" + request.getParameter("author") + "'"
+ " and qty > 0 order by price desc";
// Print an HTML page as the output of the query
out.println("<html><head><title>Query Response</title></head><body>");
out.println("<h3>Thank you for your query.</h3>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
// Step 4: Process the query result set
int count = 0;
while (rset.next()) {
// Print a paragraph <p>...</p> for each record
out.println("<p>" + rset.getString("author")
+ ", " + rset.getString("title")
+ ", $" + rset.getDouble("price") + "</p>");
count++;
}
out.println("<p>==== " + count + " records found =====</p>");
out.println("</body></html>");
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You need to load your driver before you get a connection, something like that:
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Here is a nice example: http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm
you should add this line,
Class.forName("com.mysql.jdbc.Driver");
As it is the first step to establish connection with JDBC driver,
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 1: Allocate a database Connection object
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
Provide that you added the mysql connector jar in your buidpath
As I see this jdbc:mysql://localhost:8888/ebookshop you have changed the default port of mysql from 3306 to 8888
If you did not change the port just use 3306 as the port for mysql
As the exception is saying No suitable driver found that obviously means you don't have the
mysql-connector-[version].jar in your classpath If you are using eclipse just place the jar under WEB-INF/lib and if you are using standalone tomcat just place the driver jar in the lib folder of Tomcat
try this
public static void connect() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/database_name?autoReconnect=true";
c = DriverManager.getConnection(url,"root","123");
}
thanx..

Categories

Resources