Failed to connect MySQL in IDEA 12.1.4 - java

I had learn javascript on the base of code of my web. Then, I tried to develop a new web but failed. After google, I still don't have clues. So I ask for help here. Thanks for advance.
My IDEA is 12.1.4. The install process is:
1) I make new project by selecting "JavaEE Web Module";
2) I then copy previously java script to deal with mysql, and a part of code would be listed below;
package inhouse;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
public class DBTool {
private DataSource ds = null;
private Connection conn = null;
private Statement stm = null;
private ResultSet rs = null;
private Context ctx = null;
public DBTool() throws NamingException{
this("editingphosphorylation");
}
public DBTool(String dbName) throws NamingException{
try{
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/" + dbName);
}
catch (NamingException e) {
throw new NamingException("Can't get DataSource from pool: " + e.getMessage());
}
}
public Connection getConnection() throws SQLException{
conn = ds.getConnection();
return conn;
}
......
}
3) Add "resource-ref" to WEB-INF/web.xml;
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/editingphosphorylation</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
4) Download "mysql-connector-java-5.1.40-bin.jar", and put it to WEB-INF/lib;
5) With "View-Tool Windows-Database", I confirm mysql database could be accessed;
6) But when start tomcat, it output following error:
HTTP Status 500 - An exception occurred processing JSP page /geneList.jsp at line 26
type Exception report
message An exception occurred processing JSP page /geneList.jsp at line 26
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /geneList.jsp at line 26
23:
24: try{
25: db = new DBTool();
26: conn = db.getConnection();
27: //Class.forName("com.mysql.jdbc.Driver").newInstance();
28: //Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/editingphosphorylation","2pm","editingphosphorylation");
29: pst = conn.prepareStatement("select * from gene_sequence where geneName = ?");
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
javax.servlet.ServletException: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:916)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:845)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:147)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
inhouse.DBTool.getConnection(DBTool.java:39)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:524)
sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:493)
sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307)
java.sql.DriverManager.getDriver(DriverManager.java:262)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
inhouse.DBTool.getConnection(DBTool.java:39)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Any geneList.jsp is like this
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="inhouse.*, java.sql.*" %>
<%# page import="java.io.*" %>
<html>
<head>
<title>get gene list</title>
</head>
<body>
<% String geneName = request.getParameter("geneName");
DBTool db;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
db = new DBTool();
conn = db.getConnection();
//Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/editingphosphorylation","2pm","editingphosphorylation");
pst = conn.prepareStatement("select * from gene_sequence where geneName = ?");
pst.setString(1, geneName);
rs = pst.executeQuery();
if(rs.next()){
rs.beforeFirst();%>
<table>
<th>
<td>Gene Name</td><td>Transcript Name</td><td>DNA Sequence</td><td>Protein Sequence</td>
</th>
<%while(rs.next()){
String geneNameRetrieve = rs.getString("geneName");
String transcriptNameRetrieve = rs.getString("transcriptName");
String dnaSequenceRetrieve = rs.getString("dnaSequence");
String proteinSequenceRetrieve = rs.getString("proteinSequence"); %>
<tr>
<td><%=geneNameRetrieve%></td><td><%=transcriptNameRetrieve%></td><td><%=dnaSequenceRetrieve%></td><td><%=proteinSequenceRetrieve%></td>
</tr><%
}%>
</table>
<%}else{%>
<div>No data.</div>
<%}
DBTool.close(rs, pst);
}finally {
DBTool.close(conn);
}%>
</body>
</html>
Compare with previously project, and according to google, I found the new project lack META-INF directory, so I make a new directory in web, and put a new context.xml into it.
<?xml version='1.0' encoding='utf-8'?>
<Context path="/">
<Loader delegate="true" />
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/editingprosphorylation" auth="Container" type="javax.sql.DataSource"
maxActive="555" maxIdle="50" maxWait="10000"
timeBetweenEvictionRunsMillis="60000"
username="2pm" password="editingprosphorylation" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/editingprosphorylation"/>
</Context>
However, it doesn't work. After google, I hardly don't know how to do, Any suggestion would be grateful!

Typo:
editingphosphorylation (editingpHosphorylation)
editingprosphorylation (editingpRosphorylation)

Related

NullPointerException in conn = this.jdbcFactory.getConnection();

I am using Java 1.4 and tomcat v4.0.
This is the code in my Dao:
private DataSource jdbcFactory;
public CommonDao() {
Context c = null;
if (this.jdbcFactory == null) {
try {
c= new InitialContext();
Context envCtx = (Context)c.lookup("java:comp/env");
this.jdbcFactory = (DataSource)envCtx.lookup("jdbc/mydb");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
public String getParamValue(String param_name) throws SQLException, TestException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sqlString=null;
String param_value = null;
TestException fe = new TestException();
sqlString = "SELECT PARAM_VALUE " +
"FROM SAMPLE_TBL " +
"WHERE PARAM_NAME = '" + param_name + "' " ;
try {
conn = this.jdbcFactory.getConnection();
ps = conn.prepareStatement(sqlString);
rs = ps.executeQuery();
while (rs.next()) {
param_value = rs.getString("PARAM_VALUE");
}
} catch(SQLException e){
fe.setCallingObj("CommonDao.getParamValue");
fe.setErrorCode(e.getErrorCode());
fe.setErrorMessage(e.getMessage());
fe.setStackTrace(e.getStackTrace());
throw fe;
} catch (Exception e) {
e.printStackTrace();
} finally {
rs.close();
ps.close();
conn.close();
}
return param_value;
}
context.xml under META-INF:
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/mydb" global="jdbc/mydb" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
url="jdbc:oracle:thin:#somesitexxx:xxxx:XXXXXX"
username="someusername" password="somepass" maxActive="1000"
maxIdle="1000" maxWait="500" />
</Context>
web.xml under WEB-INF:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app id="WebApp_ID">
<servlet>
<servlet-name>LoginController</servlet-name>
<display-name>LoginController</display-name>
<description></description>
<servlet-class>com.Controller.LoginController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginController</servlet-name>
<url-pattern>/LoginController</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>jdbc/rdcdb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
I am using ojdbc7-12.1.0.2.jar as well but included or not I am still getting the NPE in conn = this.jdbcFactory.getConnection();
this.jdbcFactory -> is also null when debugging.
Can you help me which part I miss?
EDIT: I have now upgraded to java 8 and tomcat 7 and used ojdbc7-12.1.0.2.jar.
But I am still getting the NPE exception
updated error stacktrace:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.driver.OracleDriver'
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1429)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at com.Dao.CommonDao.getParamValue(CommonDao.java:72)
at com.Dao.CommonDao.checkAvailability(CommonDao.java:411)
at com.Controller.LoginController.processRequest(LoginController.java:114)
at com.Controller.LoginController.doGet(LoginController.java:64)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.driver.OracleDriver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420)
... 27 more
Apr 28, 2022 3:16:40 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [LoginController] in context with path [/BV_PROBE] threw exception
java.lang.NullPointerException
at com.Dao.CommonDao.getParamValue(CommonDao.java:89)
at com.Dao.CommonDao.checkAvailability(CommonDao.java:411)
at com.Controller.LoginController.processRequest(LoginController.java:114)
at com.Controller.LoginController.doGet(LoginController.java:64)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
It catches SQLException: Cannot load JDBC driver class 'oracle.jdbc.driver.driver.OracleDriver'
Assuming that that is the only constructor ...
If jdbcFactory is null, that means that in the following code:
try {
c = new InitialContext();
Context envCtx = (Context) c.lookup("java:comp/env");
this.jdbcFactory = (DataSource) envCtx.lookup("jdbc/mydb");
} catch (NamingException e) {
e.printStackTrace();
}
either the second lookup call returned null or you threw and caught a NamingException. According to the Context javadocs, a lookup call may return null, it your application bound null to the name.
However ... on rereading your question, I noticed this:
I am using Java 1.4 and Tomcat v4.0.
These are truly ancient versions. Both are end-of-life. Tomcat 4 was end-of-life prior to 20121, and Java 1.4.2 in 2013. You are missing nearly 10 years worth of security patches.
And this:
I am using ojdbc7-12.1.0.2.jar
That is a driver for Java 7. I doubt that it will work with Java 1.4.
According to what I have read, you should be using an ojdbc.14 driver with Java 1.4. It is highly unlikely that you can find one that is compatible with a recent Oracle database.
1 - 2012 is when Tomcat 5 was officially end-of-life. The end-of-life for earlier versions was not formally announced. But the last patch release of Tomcat 4 was in 2009.

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.

"Resource not available" Error for displaying database into a JSP

I think i have got the successful connection to the database and when i run the Fetch.jsp, i do get the page with the Submit button. But when i click on submit button it shows an Tomcat Error type Status Report message /Sample description The Requested Resource is not available.
Tools:Eclipse Kepler
MySQL Workbench 6.1.7
Apache Tomcat 7.0.54
Fetch.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Database_Test</title>
</head>
<body>
<form action="Sample" method="post">
Fetch Data: <input type="submit"></input>
</form>
</body>
</html>
Sample.java
package testusecase;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Sample extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8462790020399479519L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
#SuppressWarnings("unused")
Sample instance = new Sample();
final String URL = "jdbc:mysql://localhost:3306/samschema";
final String USER = "root";
final String PASSWORD = "password";
final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
try {
Class.forName(DRIVER_CLASS);
Connection connection = null;
connection = DriverManager.getConnection(URL, USER, PASSWORD);
String query = "SELECT * FROM samschema.sample1";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
int serial_no = rs.getInt("serial_no");
String first_name = rs.getString("first_name");
String middle_name = rs.getString("middle_name");
String last_name = rs.getString("last_name");
String date_of_birth = rs.getString("date_of_birth");
String contact_no = rs.getString("contact_no");
String email_id = rs.getString("email_id");
String residential_address = rs.getString("residential_address");
String city = rs.getString("city");
BigDecimal percentage_x = rs.getBigDecimal("percentage_x");
Date yop_x = rs.getDate("yop_x");
String board_x = rs.getString("board_x");
String percentage_xii = rs.getString("percentage_xii");
String yop_xii = rs.getString("yop_xii");
String board_xii = rs.getString("board_xii");
String btech_stream = rs.getString("btech_stream");
String mtech_stream = rs.getString("mtech_stream");
String other_stream = rs.getString("other_stream");
String percentage_graduation = rs.getString("percentage_graduation");
String mca_percentage = rs.getString("mca_percentage");
String year_of_graduation = rs.getString("year_of_graduation");
String d_to_d = rs.getString("d_to_d");
String mtech_percentage = rs.getString("mtech_percentage");
String yop_diploma = rs.getString("yop_diploma");
String percentage_d_to_d = rs.getString("percentage_d_to_d");
// print the results
System.out.format("%d, %s, %s, %s, %s, %s, %s, %s, %s, %d, %d, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\n", serial_no, first_name,
middle_name,last_name, date_of_birth,contact_no,email_id,residential_address,city, percentage_x, yop_x, board_x, percentage_xii, yop_xii, board_xii, btech_stream, mtech_stream, other_stream, percentage_graduation, mca_percentage, year_of_graduation, d_to_d, mtech_percentage, yop_diploma, percentage_d_to_d);
}
st.close();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>TestUseCase</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>TestUseCase</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
</security-constraint>
<servlet>
<description></description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<jsp-file>/Login.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Sample</display-name>
<servlet-name>Sample</servlet-name>
<servlet-class>Sample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Sample</servlet-name>
<url-pattern>/Sample</url-pattern>
</servlet-mapping>
</web-app>
Java Stack Trace in console
Java Model Exception: Java Model Status [Unknown javadoc format for getAsciiStream(java.lang.String) [in ResultSet [in ResultSet.class [in java.sql [in U:\Miller\Eclipse\JDK\lib\rt.jar]]]]]
at org.eclipse.jdt.internal.core.JavadocContents.getMethodDoc(JavadocContents.java:158)
at org.eclipse.jdt.internal.core.BinaryMethod.getAttachedJavadoc(BinaryMethod.java:671)
at org.eclipse.jdt.internal.ui.text.javadoc.JavadocContentAccess2.getHTMLContent(JavadocContentAccess2.java:499)
at org.eclipse.jdt.internal.ui.text.java.ProposalInfo.extractJavadoc(ProposalInfo.java:93)
at org.eclipse.jdt.internal.ui.text.java.ProposalInfo.computeInfo(ProposalInfo.java:77)
at org.eclipse.jdt.internal.ui.text.java.ProposalInfo.getInfo(ProposalInfo.java:62)
at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.getAdditionalProposalInfo(AbstractJavaCompletionProposal.java:573)
at org.eclipse.jface.text.contentassist.AdditionalInfoController$3.run(AdditionalInfoController.java:106)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)
Browser Error
HTTP Status 500 - Error instantiating servlet class Sample
type Exception report
message Error instantiating servlet class Sample
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class Sample
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.ClassNotFoundException: Sample
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.54 logs.
Apache Tomcat/7.0.54
In the servlet tag, the <servlet-class> element should be the fully qualified name of your servlet class. For example:
<servlet-class>testusecase.Sample</servlet-class>
Also note that the stack trace you show appears to be for when your app is starting up, and not when the specified problem occurs.
According to the stacktrace, the servlet /Placement tries to give control to Fetch.jsp and container fails to find it. It could be a lower/upper case problem, or is it really at root of web application ?
With the full error it is clear. In the web.xml file, you must give the fully qualified name of your servlet class :
<servlet-class>testusecase.Sample</servlet-class>

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

NullPointerException caused by not accessing database from JSP

I am working on a project that is accessing PostgreSQL with a jdbc driver and process this data through a middleware and finally displays/updates via jsp pages. Using Eclipse I created a Dynamic Web Project. Then I have written code for all back-end and middleware operations. I can access database from static context (I mean main method of java sources). I can also use my java resources (e.g displaying) from jsp if I don't call any methods that are accessing database. But when I try to access database, it doesn't work and gives me a null pointer exception.
<jsp:useBean id="user" class="dbActionManagement.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>next page</title>
</head>
<body>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</body>
</html>
This gives me:
SEVERE: Servlet.service() for servlet [jsp] in context with path
[/GNYSweb] threw exception [java.lang.NullPointerException] with root
cause java.lang.NullPointerException at
dbActionManagement.OfficerManager.getTotalPoint(OfficerManager.java:494)
at dbActionManagement.UserData.getUsername(UserData.java:28) at
org.apache.jsp.NextPage_jsp._jspService(NextPage_jsp.java:80) at
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) 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$Worker.runTask(Unknown
Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown
Source) at java.lang.Thread.run(Unknown Source)
Also java class that I am using for this is UserData and method getUserName()
public String getUsername() {
int a = new OfficerManager().getTotalPoint("a");
return new Integer(a).toString();
}
OfficerManager has a default constructor and getTotalPoint is
public int getTotalPoint(String officerId){
int point = 0;
ResultSet results = null;
try {
if(DBConnection.db.isClosed()){ // problem is caused by this line
DBConnection.connect();
}
Statement sql = DBConnection.db.createStatement();
String sqlText = "select point from officers ";
sqlText += " where sicilno = '" + officerId + "'";
results = sql.executeQuery(sqlText);
} catch (SQLException e) {
e.printStackTrace();
}
if(results != null)
try {
while(results.next()){
point = (int) results.getDouble("point");
}
} catch (SQLException e) {
e.printStackTrace();
}
return point;
}
I have added postgreSQL jdbc driver to my build path. Also I included same jdbc driver in the lib folder of Tomcat. Also I am using an instance of Tomcat v7.0 at localhost and the location of this is [workspace metadata]
I understand the problem, it is basically I was trying to reach Connection object that is null. I use static objects for accessing database, I forgot to initialize them before using. There are several solutions for this, the most basic one is to write another method in UserData class called startConnection()
public void startConnection(){
new DBConnection("myDBName", "myUserName", "myPassword");
}
and call this method from jsp pages
...
<body>
<% user.startConnection(); %>
Name: <%= user.getUsername() %><BR>
</body>
...
That way I can initialize my DBConnection class instances properly before using them. Thanks for your help.
Avoid checking if the db is closed before connection is created, comment out:
//if(DBConnection.db.isClosed()){ // problem is caused by this line
DBConnection.connect();
// }
And then close the connection after using it and when an exception occurs. Your exception block should be changed to;
catch (SQLException e)
{
e.printStackTrace();
if((DBConnection !=null) && DBConnection.db !=null && !DBConnection.db.isClosed())
{
BConnection.db.close();
}
}
And also close it in the try block straight after usage.
As rule of thumb - alway check if the connection is not null before attempt closing it.
try doing something like this:
if((DBConnection !=null) && DBConnection.db !=null && DBConnection.db.isClosed())
{
DBConnection.connect();
}

Categories

Resources