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(...);
Related
Hello i am new to stackoverflow.Recently i developed a project with login,Registration page using java servlets and database.Yesterday my code runs with correct only(if i put wrong credentials,it shows"Data not found ,click on register")..Today i run the same code,with putting wrong credentials,it automatically login without validating.Please resolve my issues.Hereby i attached my code
MyShopDAOimplcode
package login.sg.registration;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class ShopDAOimpl implements ShopDAO {
static Connection con;
static PreparedStatement ps;
#Override
public int insertShopName(Shop s) {
int status=0;
try {
con=MyConnectionProvider.getCon();
ps=con.prepareStatement("insert into shop123 (id,shopName,password,ownerName,address) values(?,?,?,?,?)");
ps.setString(1, s.getId());
ps.setString(2, s.getShopname());
ps.setString(3, s.getPassword());
ps.setString(4, s.getName());
ps.setString(5, s.getAddress());
//System.out.println("new comment" + s.getShopname());
status=ps.executeUpdate();
System.out.println("insert ps " + ps);
con.close();
}catch(Exception e) {
System.out.println(e);
}
return status;
}
#Override
public Shop getShop(String Shopname, String pass) {
Shop s= new Shop();
try {
con=MyConnectionProvider.getCon();
//System.out.println("after connection");
ps=con.prepareStatement("select * from shop123 where shopname=? and password=?");
ps.setString(1, Shopname);
ps.setString(2, pass);
//System.out.println(ps);
System.out.println(Shopname);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
s.setShopname(rs.getString(1));
s.setPassword(rs.getString(2));
s.setName(rs.getString(3));
}
}catch(Exception e) {
System.out.println(e);
}
return s;
}
}
my LoginRegister code
package login.sg.registration;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/LoginRegister")
public class LoginRegister extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginRegister() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ShopDAO S= new ShopDAOimpl();
String submitType=request.getParameter("submit");
if(submitType.equals("login")){
String shopName=request.getParameter("name");
// System.out.println(shopName);
String password=request.getParameter("password1");
Shop s=S.getShop(shopName, password);
System.out.println(s.getShopname()+s.getPassword());
request.setAttribute("message", s.getName());
request.getRequestDispatcher("Home.jsp").forward(request, response);
}else if(submitType.equals("register")) {
//System.out.println("register now function starts");
Shop s = new Shop();
s.setShopname(request.getParameter("shopname"));
//System.out.println("test comment " +request.getParameter("shopname"));
s.setPassword(request.getParameter("password1"));
s.setName(request.getParameter("name"));
s.setAddress(request.getParameter("address"));
s.setId(request.getParameter("id"));
request.getParameter ("password1");
S.insertShopName(s);
request.setAttribute("successMessage","Registration Sucessfull!!!...login using your credentials");
request.getRequestDispatcher("login.jsp").forward(request, response);
}else {
request.setAttribute("message","Data Not Found,click on Register !!!");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
Your code should look like this:
Shop s = S.getShop(shopName, password);
System.out.println(s.getShopname() + s.getPassword());
if (null != s.getName()) {
request.setAttribute("message", s.getName());
request.getRequestDispatcher("Home.jsp").forward(request, response);
} else {
request.setAttribute("message", "Data Not Found,click on Register !!!");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
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) {};
}
i am trying to do java database connectivity in eclipse juno using eclipse but i am getting the following error comes
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException
suggest me some solutions..........
this is my code :
package example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Connect {
public static Connection getConnection()
{
String url="jdbc:mysql://localhost:3306/demo";
String drive="com.mysql.jdbc.Driver";
//String databse="demo";
String user="root";
String password="abc";
Connection conn=null;
try
{
Class.forName(drive);
conn=DriverManager.getConnection(url, user, password);
}
catch (Exception e)
{
System.out.println(""+e);
}
return conn;
}
public static void main(String[] args)
{
Connection conn=null;
PreparedStatement pstmt=null;
try
{
conn=getConnection();
conn.setAutoCommit(false);
pstmt=conn.prepareStatement("insert into testlongtele(address,name)values(?,?)");
pstmt.setString(0, "NIRAV");
pstmt.setString(1, "KAMANI");
pstmt.executeUpdate();
pstmt.close();
conn.commit();
conn.close();
}
catch(Exception e)
{
System.out.println(""+e);
}
}
}
From This link:
Possible Cause of this error is:
1) You don't have mysql-connector.jar in your Classpath. as stated earlier this jar file contains "com.mysql.jdbc.Driver" class it must be present in classpath in order to successful connection to mysql database. you can downlad mysql-connector.jar from mysql.com.
2) mysql-connector.jar is in your classpath but somehow your classpath is getting overridden.
Classpath is tricky in Java and classpath specified in jar may override CLASSPATH path variable. See how classpath works in Java to understand this issue in detail.
3) mysql-connector.jar is in classpath but current user doesn't have read permission.
This problem often happens in Unix or Linux operating system which has sophisticated file and directory permission based on user, group and owner level. just get the right permission and run your program again.
You can add:
class.forName(driver).newInstance();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mindtree.kalinga.exception.ConnectionfailedException;
public class JdbcConnection {
private static JdbcConnection jdbcConnection;
private static Connection dbConnection;
private JdbcConnection() {
}
public static JdbcConnection getInstance() {
if (jdbcConnection == null)
jdbcConnection = new JdbcConnection();
return jdbcConnection;
}
public static void createConnection() throws ConnectionfailedException {
try {
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mindtree", "root", "Welcome123");
} catch (SQLException e) {
throw new ConnectionfailedException("Error creating the connection to database", e);
}
System.out.println("Connection to db Established!");
}
public static Connection getConnection() {
return dbConnection;
}
public static void closeConnection() throws ConnectionfailedException {
try {
dbConnection.close();
} catch (SQLException e) {
throw new ConnectionfailedException("connection not closed properly", e);
}
}
}
--------------------------------------
Main
--------------------------------------
package com.mindtree.kalinga.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.exception.ConnectionfailedException;
import com.mindtree.kalinga.service.Mindtreeservice;
import com.mindtree.kalinga.serviceimp.Mindtreeserviceimp;
import com.mindtree.kalinga.utility.JdbcConnection;
public class MindtreeMain {
static Scanner in = new Scanner(System.in);
static Mindtreeservice ms = new Mindtreeserviceimp();
public static void main(String[] args) {
try {
JdbcConnection.createConnection();
} catch (ConnectionfailedException e) {
System.out.println("Not able to connect to database! Terminating application!");
e.printStackTrace();
}
MindtreeMain mm = new MindtreeMain();
int i = 1;
while (i == 1) {
System.out.println("1. to enter the detail\n" + "2. fetch the detail\n" + "3. to exit");
int key = in.nextInt();
switch (key) {
case 1:
Mindtree m = mm.createminds();
break;
case 2:
List<Mindtree> ml = new ArrayList<>();
mm.display(ml);
break;
case 3:
i = 0;
break;
default:
break;
}
}
}
private Mindtree createminds() {
// TODO Auto-generated method stub
System.out.println("enter the id of mind");
int id = in.nextInt();
in.nextLine();
System.out.println("enter the name of mind");
String name = in.nextLine();
System.out.println("ente the address of minds");
String address = in.nextLine();
Mindtree m = new Mindtree(id, name, address);
return m;
}
private void display(List<Mindtree> mind) {
for (Mindtree i : mind) {
System.out.println(i.getMid());
System.out.println(i.getName());
System.out.println(i.getAddress());
}
}
}
-------------------------------------------------
service
-------------------------------------------------
import java.util.List;
import com.mindtree.kalinga.entity.Mindtree;
public interface Mindtreeservice {
public void insertmind(Mindtree m);
public List<Mindtree> getAllminds();
}
---------------------------------------------
serviceimp
---------------------------------------------
package com.mindtree.kalinga.serviceimp;
import java.util.List;
import com.mindtree.kalinga.dao.Mindtreedao;
import com.mindtree.kalinga.daoimp.Mindtreedaoimp;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.service.Mindtreeservice;
public class Mindtreeserviceimp implements Mindtreeservice {
Mindtreedao md = new Mindtreedaoimp();
#Override
public void insertmind(Mindtree m) {
// TODO Auto-generated method stub
md.insertMindToDb(m);
}
#Override
public List<Mindtree> getAllminds() {
// TODO Auto-generated method stub
return md.getAllMindFromDb();
}
}
--------------------------------------------
dao
--------------------------------------------
import java.util.List;
import com.mindtree.kalinga.entity.Mindtree;
public interface Mindtreedao {
public void insertMindToDb(Mindtree m);
public List<Mindtree> getAllMindFromDb();
}
-------------------------------------------
daoimp
-------------------------------------------
package com.mindtree.kalinga.daoimp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mindtree.kalinga.dao.Mindtreedao;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.utility.JdbcConnection;
import com.mysql.jdbc.Statement;
public class Mindtreedaoimp implements Mindtreedao {
#Override
public void insertMindToDb(Mindtree m) {
Connection con = JdbcConnection.getConnection();
String query = "insert into mindtree values(?,?,?);";
PreparedStatement ps = null;
try {
ps = con.prepareStatement(query);
ps.setInt(1, m.getMid());
ps.setString(2, m.getName());
ps.setString(3, m.getAddress());
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
#Override
public List<Mindtree> getAllMindFromDb() {
// TODO Auto-generated method stub
List<Mindtree> mtl = new ArrayList<Mindtree>();
Connection con = JdbcConnection.getConnection();
String query = "select * from mindtree;";
Statement st = null;
ResultSet rs = null;
try {
st = (Statement) con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
Mindtree m = new Mindtree(rs.getInt(1), rs.getString(2), rs.getString(3));
mtl.add(m);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mtl;
}
}
-----------------------------------------------
exception
package com.mindtree.kalinga.exception;
public class ConnectionfailedException extends Exception {
public ConnectionfailedException() {
super();
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
-----------------------------
entity
-----------------------------
package com.mindtree.kalinga.entity;
public class Mindtree {
int Mid;
String name;
String address;
public Mindtree(int mid, String name, String address)
{
Mid = mid;
this.name = name;
this.address = address;
}
public int getMid() {
return Mid;
}
public void setMid(int mid) {
Mid = mid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
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.
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.