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.
Adding mysql-connector-java-5.1.11-bin.jar file to WEB-INF/lib folder fixed my problem.
Related
I want to get the list of all database names from a Sybase DB server. I can connect the Sybase db through Java, but don't know how to get the list of database names. I am using jconn4 jar file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.SybDriver;
public class ConnectToSybase {
public static Connection conn = null;
public static Statement stmt = null;
public static SybDriver sybDriver = null;
public static ResultSet rs = null;
public static String dbServerIP = "10.10.10.11";
public static String portNo = "5000";
public static String dbName = "NewDB";
public static void main(String[] args) {
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
conn = DriverManager.getConnection("jdbc:sybase:Tds:" + dbServerIP + ":" + portNo, "usrname", "password");
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("In exception");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}
}
I found myself a working code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.SybDriver;
public class ConnectToSybase {
public static Connection conn = null;
public static Statement stmt = null;
public static SybDriver sybDriver = null;
public static ResultSet rs = null;
public static String dbServerIP = "10.10.10.11";
public static String portNo = "5000";
public static String dbName = "NewDB";
public static void main(String[] args) {
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
conn = DriverManager.getConnection("jdbc:sybase:Tds:" + dbServerIP + ":" + portNo, "usrname", "password");
stmt = conn.createStatement();
List<String> dbList = new ArrayList<String>();
// getting list of DB names from the DB server
ResultSet rs = conn.getMetaData().getCatalogs();
while (rs.next()) {
dbList.add(rs.getString(1));
}
for (String list : dbList) {
System.out.println(list);
}
} catch (Exception e) {
System.out.println("In exception");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}
}
I am a student learning JSP, and I seem to have this issue in executing a method via an object of a DAO class. When the database connectivity and SQL query is given on the servlet itself it, it will work. But when given in the DAO class and a object is used, it doesn't work. Please help.
import dataaccessobjects.cartDAO1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class addtoCartServ extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
cartDAO1 newcart = new cartDAO1();
PrintWriter out = response.getWriter();
if (request.getParameter("submit") != null){
//out.println("added to cart");
try {
//out.println("submit not null");
String Uname = (String) request.getSession().getAttribute("Welcome");
String ino = request.getParameter("ino");
String iqnty = request.getParameter("quantity");
String iname = request.getParameter("iname");
if(newcart.addToCart(iname,Uname,ino,iqnty)){
out.println("added to cart");
}
} catch (SQLException ex) {
Logger.getLogger(addtoCartServ.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(addtoCartServ.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
The DAO class
public cartDAO1(){
}
public boolean addToCart(String iname,String username, String ino,String iqnty) throws SQLException, ClassNotFoundException{
boolean flag = false;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/styleomega","root","");
PreparedStatement ps = conn.prepareStatement("INSERT INTO cart(iname,uname,ino,iqnty) VALUES (?,?,?,?)");
// set the values for parameters
ps.setString(1,iname);
ps.setString(2,username);
ps.setString(3,ino);
ps.setString(4,iqnty);
int rs = ps.executeUpdate();
if (rs==1){
flag = true;
}
return flag;
}
}
You should be import the DAO class package in servlet then access it it will work like
import DAO.cartDao;
If you will not import then how to acces it
I don't understand exactly what is not working? But I have noticed, you're not closing statement and the database connection in your DAO class.
FYI: An example
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = // Retrieve connection
stmt = conn.prepareStatement(// Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
try { if (conn != null) conn.close(); } catch (Exception e) {};
}
Following is my servlet:
import java.io.IOException;
import java.sql.*;
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 connection.Connection;
#WebServlet("/Check")
public class Check extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
Connection con;
//PreparedStatement pstmt=con.prepareStatement("Insert into account_master(name,acct_opn_date,cif_id,address) values(?,?,?,?)");
PreparedStatement pstmt= con.prepareStatement("Insert into account_master(name,acct_opn_date,cif_id,address) values(?,?,?,?)");
}
Here in the last statement, I am getting error in Eclipse
**Multiple markers at this line
Watchpoint:Check [access and modification] - pstmt
The method prepareStatement(String) is undefined for the type
Connection**
Following is my connection class:
package connection;
import java.sql.*;
public class Connection {
public static void main(String args[])
{
String username="system";
String password="root";
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
try {
DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE",username,password);
//DriverManager.getConnection("jdbc:oracle:thin:system/root#localhost:1521:XE");
} catch (SQLException e) {
System.err.println("Problem in connection");
e.printStackTrace();
}
}
catch(ClassNotFoundException ex)
{
System.err.println("Error loading driver");
}
}
}
You are confusing the JDBC Connection class with your own connection class.
You can rename your connection class to a ConnectionBuilder class:
public class ConnectionBuilder {
String username="system";
String password="root";
public static Connection buildConnection () {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
try {
return DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE",username,password);
} catch (SQLException e) {
System.err.println("Problem in connection");
e.printStackTrace();
return null; // better throw an exception
}
} catch(ClassNotFoundException ex) {
System.err.println("Error loading driver");
return null; // better throw an exception
}
}
}
And your Check class should use this method:
PreparedStatement pstmt = ConnectionBuilder.buildConnection().prepareStatement(...);
The following is a servlet for getting parameter from a jsp page.
I am trying to run following code --
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.swing.JFrame;
public class oneServlet extends HttpServlet {
public static Connection getConnection() throws Exception {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://10.1.11.112:5432/pack";
String username = "pack";
String password = "pack";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) throws Exception {
String user=request.getParameter("t1");
String pass=request.getParameter("t2");
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String queryTest = "select username,password from login";
pstmt = conn.prepareStatement(queryTest);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && pass.equals(password))
{
JFrame frame = new JFrame("/LoginSuccess.jsp");
}
else
{
System.out.println("Login Failed,Please try Againe");
}
}}
catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
}
}
It's showing error in request.getParameter that " request cannot be resolved. Can anyone help me resolve this.
When you extends HttpServlet, you need to override doGet and doPost() which take HttpServletRequest and HttpServletResponse as parameters.
Example:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
.......
String user=request.getParameter("t1"); //Use request variable to do get...
}
Read more here and here
Servlets doesnt have main() , they are executed by SelvletContainer or Webserver (like tomcat)
In your scenario.
public void doGet(){
String user=request.getParameter("t1");
String pass=request.getParameter("t2");
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String queryTest = "select username,password from login";
pstmt = conn.prepareStatement(queryTest);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && pass.equals(password))
{
//JFrame frame = new JFrame("/LoginSuccess.jsp");
request.getRequestDispatcher().redirect("/LoginSuccess.jsp");
}
else
{
System.out.println("Login Failed,Please try Againe");//This will print at the console
}
}}
catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
Learn more about servlets
This is my CreateQuery.java class .
package DbConnect;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CreateQuery {
Connection conn;
public CreateQuery() throws ClassNotFoundException, SQLException, IOException {
conn=new DbAccess().returnDatabaseConnection();
}
public int addNewLayertoDB(){
try {
PreparedStatement statement = null;
//String table_name = feature_name + "_" + shape;
String query = "SELECT the_geom from bbmp ";
statement = conn.prepareStatement(query);
//statement.setString(1, feature_name);
ResultSet rs = statement.executeQuery();
rs.close();
return 1;
} catch (SQLException ex) {
System.out.println("Sql exception");
return 0;
}
}
public void closeConn() throws SQLException {
if (conn != null) {
this.conn.close();
}
}
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
CreateQuery cq = new CreateQuery();
cq.addNewLayertoDB();
cq.closeConn();
}
}
This is my DbConnect class
package DbConnect;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class DbAccess{
public static void main(String[] argv) {
System.out.println("-------- PostgreSQL " +
"JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/Ethermap","postgres", "*******");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null){
System.out.println("You made it, take control your database now!");
}else{
System.out.println("Failed to make connection!");
}
}
public Connection returnDatabaseConnection() {
System.out.println("DB not connected");
return null;
}
}
The error I am getting when I run CreateQuery is
DB not connected
Exception in thread "main" java.lang.NullPointerException
at DbConnect.CreateQuery.addNewLayertoDB(CreateQuery.java:24)
at DbConnect.CreateQuery.main(CreateQuery.java:45)
What is the error ? And How do I debug it ?
The method returnDatabaseConnection() that you call in the constructor of CreateQuery always returns null, so it's not a surprise that your connection object is null.