0

I was trying to connect mysql database in my servlet. Then I'm getting an exception.
But when I am testing the database connection from a usual Java class the connection is ok and I getting the data from the database.
The exception I'm getting on tomcat server console is: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver .
The code of my DatabaseHandler.java is:

import java.sql.*;
public class DatabaseHandler {
private Statement stmt;
private Connection con;
String username = "root";
String password = "thunder";
String dbname = "bidderboy";
public DatabaseHandler()
{
    this.createConnection();
}

private void createConnection()
{
    //create the connection for first time
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con = DriverManager.getConnection("jdbc:mysql://localhost/"+dbname , username , password);
        stmt = con.createStatement();

    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}
public int executeUpdate(String sql)
{
    int result = 0;

    //before update checks if connection is open
    try {
        if(con.isClosed()) {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql://localhost/"+dbname , username , password);
            stmt = con.createStatement();
        }
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }

    //try to executeUpdate the sql command
    try{
        result = stmt.executeUpdate(sql);
    }
    catch(Exception ex){
        System.out.println("Couldn't executeUpdate sql command");
    }
    return result;
}

public ResultSet executeQuery(String sql)
{
    ResultSet rs = null;
    //before Query checks if connection is open
    try {
        if(con.isClosed()) {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dbname , username , password);
            stmt = con.createStatement();
        }
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }

    //try to executeQuery the sql command
    try{
        rs = stmt.executeQuery(sql);
    }
    catch(Exception ex){
        System.out.println("Couldn't executeQuery sql command");
    }
    return rs;
}

public void closeConnection()
{
    //if connection is open try to close the connection
    try {
        if(!con.isClosed()) {
            con.close();
        }
    } catch (SQLException ex) {
        System.out.println("Failed to close database connection");
    }
}
}

The code of my servlet is:

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@SuppressWarnings("serial")
public class UserLogin extends HttpServlet{

public UserLogin()
{

}

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    DatabaseHandler dbh = new DatabaseHandler();
    String username="mamun";
    String password="1234";

    String dbusername="";
    String dbpassword="";

    String sql = "select * from users where username='"+username+"' and password='"+password+"'";
    ResultSet rs = dbh.executeQuery(sql);
    try {
        while(rs.next())
        {
            dbusername = rs.getNString(1);
            dbpassword = rs.getNString(2);
        }
    } catch (SQLException e) {}
    System.out.println(dbusername+" "+dbpassword);
}
}

And the Code of normal java class from which I'm getting my data is:

import java.sql.ResultSet;
import java.sql.SQLException;

public class DatabaseConnectionTest {

public static void main(String[] args) {
    String sql = "Select * from users";
    DatabaseHandler dbh = new DatabaseHandler();

    ResultSet rs = dbh.executeQuery(sql);

    try {
        while(rs.next())
        {
            String n = rs.getNString(1);
            String c = rs.getNString(2);
            System.out.println("Name: "+n+" Contact: "+c);
        }
    } catch (SQLException ex) {
        System.out.println(ex.toString());
    }
}
}

Anybody please explain why I'm getting this class not found exception and What can be the solution. Thanks in advance.

Mamun Sardar
  • 2,679
  • 4
  • 36
  • 44
  • 6
    Make sure you have mysql jdbc jar in lib folder. – kosa Mar 13 '13 at 14:21
  • 1
    Add `jar` with `com.mysql.jdbc.Driver` to your classpath. – bsiamionau Mar 13 '13 at 14:21
  • There are soooo many questions about this on SO. – Sotirios Delimanolis Mar 13 '13 at 14:23
  • ClassNotFoundException is what it says: Class Not Found. It even gave you the name of the class it couldn't find : com.mysql.jdbc.Driver. So - check all you jars in the classpath (most likely in WEB-INF/lib) and see if you are missing the one which contains com.mysql.jdbc.Driver, probably called something like mysql-connector-java-(version).java – NickJ Mar 13 '13 at 14:53
  • OK.Thanks NickJ. Got it. – Mamun Sardar Mar 13 '13 at 15:00
  • possible duplicate of [MySQL jdbc driver and Eclipse: ClassNotFoundexception com.mysql.jdbc.Driver](http://stackoverflow.com/questions/2353141/mysql-jdbc-driver-and-eclipse-classnotfoundexception-com-mysql-jdbc-driver) – BalusC Mar 14 '13 at 03:21

1 Answers1

1

Adding mysql-connector-java-5.1.11-bin.jar file to WEB-INF/lib folder fixed my problem.

Hardik Mishra
  • 14,779
  • 9
  • 61
  • 96
Mamun Sardar
  • 2,679
  • 4
  • 36
  • 44