I'm learning to program in java and the use of servlet and jsp page.
I have some trouble understanding how I can make the connection with the database.
In particular I have a Java page called Database.java where I create the connection with the database and in which there are all the functions that are performed.
And I created a page called Prenotation.java where I have to do some actions. My problem is that I would not like to leave the database connection on this page (as you can see from the code) but I would like to make the connection via the Database.java page.
I've tried several times but I do not understand how I can do it.
Can you give me some advice? Thank you.
Database.java
package db;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;
import entity.*;
public class Database {
private Connection connection = null;
private PreparedStatement statement = null;
private ResultSet rs = null;
private String dbname = "Hotel";
String nomeutente = "root";
String password = "123456789";
private static Database db = null;
public static synchronized Database getDatabase() {
if (db == null) {
db = new Database();
}
return db;
}
private Database() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + dbname
+ "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
nomeutente, password);
} catch (Exception exc) {
exc.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
public boolean checkUser(String email, String password) throws SQLException {
boolean result = false;
String query = "select password from users where email=?";
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs = statement.executeQuery();
if (rs.next() && password.equals(rs.getString("password"))) {
result = true;
}
rs.close();
statement.close();
return result;
}
public boolean existingMail(String email) throws SQLException {
String query = "select * from users where email=?";
boolean result = true;
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs = statement.executeQuery();
if (rs.next()) {
result = true;
} else {
result = false;
}
rs.close();
statement.close();
return result;
}
public boolean insertUtente(Utente u,String password) throws SQLException {
String query = "INSERT INTO users (email,nome,cognome,luogodinascita,datadinascita,indirizzo,password) VALUES (?,?,?,?,?,?,?)";
if(existingMail(u.getEmail())) {
return false;
}
statement = connection.prepareStatement(query);
statement.setString(1, u.getEmail());
statement.setString(2, u.getNome());
statement.setString(3, u.getCognome());
statement.setString(4, u.getLuogodinascita());
statement.setString(5, u.getDatadinascita());
statement.setString(6, u.getIndirizzo());
statement.setString(7, password);
statement.execute();
statement.close();
return true;
}
public Utente getUtente(String email) throws SQLException {
String query= "select * from users where email=?";
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs=statement.executeQuery();
if(!rs.next()) {
return null;
}
Utente u=new Utente(email,rs.getString("nome"),rs.getString("cognome"),rs.getString("datadinascita"),rs.getString("luogodinascita"),rs.getString("indirizzo"));
rs.close();
statement.close();
return u;
}
public boolean modificaPassword(String email, String password) throws SQLException {
String query="UPDATE users SET password='"+password+"' WHERE email='"+email+"'";
Statement statement=connection.createStatement();
statement.executeUpdate(query);
statement.close();
return true;
}
public boolean modificaProfilo(Utente u) throws SQLException {
String query="UPDATE users SET nome = ?, cognome = ?, datadinascita = ?, luogodinascita = ?, indirizzo = ? WHERE email = ?";
statement = connection.prepareStatement(query);
statement.setString(1, u.getNome());
statement.setString(2, u.getCognome());
statement.setString(3, u.getDatadinascita());
statement.setString(4, u.getLuogodinascita());
statement.setString(5, u.getIndirizzo());
statement.setString(6, u.getEmail());
statement.executeUpdate();
statement.close();
return true;
}}
This instead is the page of which I speak
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import db.Database;
import entity.Prenotazione;
/**
*
* #author OOPs
*/
public class Prenotation extends HttpServlet {
private static final String ResultSet = null;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
String idPrenotazione = request.getParameter("idPrenotazione");
String email = request.getParameter("email");
int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
String arrivalDate = request.getParameter("arrivalDate");
String departureDate = request.getParameter("departureDate");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
// Statement stmt = con.createStatement();
out.println("connection successfull");
int total = 0;
PreparedStatement ps = con.prepareStatement( "SELECT COUNT(*) as total FROM reservation WHERE typeRoom = ? AND (? >= arrivaldate AND ? <= departuredate) OR (? >= arrivaldate AND ? <= departuredate)");
int c = 0;
ps.setInt(++c, typeRoom);
ps.setString(++c, arrivalDate);
ps.setString(++c, departureDate);
ps.setString(++c, arrivalDate);
ps.setString(++c, departureDate);
ResultSet rs = ps.executeQuery();
// ResultSet rs2 = stmt.executeQuery(check);
out.println("<h1> Stringa check eseguito </h1>");
if( total > 0) {
// response.sendRedirect("home.jsp");
response.sendRedirect("PrenotazioneNegata.jsp");
}
else {
st.executeUpdate("insert into reservation (email,typeRoom,arrivalDate,departureDate)values ('"+email+"','"+typeRoom+"','"+arrivalDate+"','"+departureDate+"')");
response.sendRedirect("PrenotazioneAvvenuta.jsp");
}
out.println("<h1> Registrazione Eseguita </h1>");
}catch(Exception e){
out.println("Errore." +e);
}
finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
A web container will typically route requests to the same servlet instance so it needs to be thread safe. Currently, the Database class provides a single connection, which would be used by concurrent requests so it is not thread safe.
Consider creating something like a ConnectionFactory class. For example:
public class ConnectionFactory {
public Connection getConnection() {
// move all the creation code from Database class to here
// create and return a new instance
}
}
Then modify the Database class to use the factory
public class Database {
private final ConnectionFactory connectionFactory;
public Database(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
// change to private and use the factory
private Connection getConnection() {
return connectionFactory.getConnection();
}
// example method to be used by servlet
public int getTotalReservations(int typeRoom, String arrivalDate, departureDate) {
// query related code currently in serlvet goes here...
}
}
And use the servlet lifecycle init() method to create the objects so the servlet can use it. For example:
public class Prenotation extends HttpServlet {
private Database database;
#Override
public void init() throws ServletException {
super.init();
this.database = new Database(new ConnectionFactory()); // no statics needed!
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
String idPrenotazione = request.getParameter("idPrenotazione");
String email = request.getParameter("email");
int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
String arrivalDate = request.getParameter("arrivalDate");
String departureDate = request.getParameter("departureDate");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// use the method from `Database` which knows how to query the DB.
int totalReservations = database.getTotalReservations(typeRoom, arrivalDate, departureDate);
// more processing... and forward to the JSP
}
Note that Database now refers to both a USERS table and a RESERVATTIONS table. It would be better to split these into separate classes, such as UsersQuery and ReservationsQuery. They can both share the same ConnectionFactory instance.
See also:
single responsibility principle
inversion of control (injecting ConnectionFactory into Database)
servlet lifecycle
why static variables (or singletons) are/can be evil
DataSource (instead of the low level ConnectionFactory)
Related
I am facing problem. We are writting Java application as school project and we are supposed to use threads. Obviously, the application is not as complex to require threads, but we have to have them.
We decided to use threads for database communication, but we are not sure, how to use them for single methods. We created Database Transfer Object with some methods to insert entities into DB. How to use Runnable for single methods, please? To be more specific, we would like to create Runnable in methods and then add it to thread pool, but then, we would be able to get returns back.
public class EmployeeDTO {
private Employee employee;
private Connection conn;
private int id_employee;
/**
* Database connection
* #throws ClassNotFoundException
* #throws SQLException
*/
public EmployeeDTO() throws ClassNotFoundException, SQLException {
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
public EmployeeDTO(Employee employee) throws ClassNotFoundException, SQLException {
this.employee = employee;
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
/**
* Insert new Employee into database and sets it's id
* #param emp
* #throws SQLException
*/
public void insertEmployee(Employee emp) throws SQLException {
setEmployee(emp);
PreparedStatement pr = conn.prepareStatement("INSERT INTO employees "
+ "(nickname,name,surname,password_emp) "
+ "VALUES (?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
pr.setString(1, employee.getNickname());
pr.setString(2, employee.getName());
pr.setString(3, employee.getSurname());
pr.setString(4, employee.getPassword());
pr.executeUpdate();
ResultSet rs = pr.getGeneratedKeys();
while (rs.next()) {
employee.setId_employee(rs.getInt(1));
}
}
/**
* Delete an employee from database
* #param id
* #throws SQLException
*/
public void deleteEmployee(int id) throws SQLException {
PreparedStatement pr = conn.prepareStatement("DELETE FROM employees WHERE id_employee=?");
pr.setInt(1, id);
pr.executeUpdate();
}
}
To be more specific, we would like to create Runnable in methods and then add it to thread pool, but then, we would be able to get returns back.
Sounds like you want to submit Callable tasks (not Runnable) to a thread pool. When you submit a Callable<T> task to an ExecutorService, you get back a Future<T> object that you can use at a later time to wait for the result of the task.
You may want to do something like below. Your insertEmployee method will be called from call method.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.Callable;
public class EmployeeDTO implements Callable<String> {
private Employee employee;
private Connection conn;
private int id_employee;
/**
* Database connection
* #throws ClassNotFoundException
* #throws SQLException
*/
public EmployeeDTO() throws ClassNotFoundException, SQLException {
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
public EmployeeDTO(Employee employee) throws ClassNotFoundException, SQLException {
this.employee = employee;
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
/**
* Insert new Employee into database and sets it's id
* #param emp
* #throws SQLException
*/
public void insertEmployee(Employee emp) throws SQLException {
setEmployee(emp);
PreparedStatement pr = conn.prepareStatement("INSERT INTO employees "
+ "(nickname,name,surname,password_emp) "
+ "VALUES (?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
pr.setString(1, employee.getNickname());
pr.setString(2, employee.getName());
pr.setString(3, employee.getSurname());
pr.setString(4, employee.getPassword());
pr.executeUpdate();
ResultSet rs = pr.getGeneratedKeys();
while (rs.next()) {
employee.setId_employee(rs.getInt(1));
}
}
/**
* Delete an employee from database
* #param id
* #throws SQLException
*/
public void deleteEmployee(int id) throws SQLException {
PreparedStatement pr = conn.prepareStatement("DELETE FROM employees WHERE id_employee=?");
pr.setInt(1, id);
pr.executeUpdate();
}
/**
* Computes a result, or throws an exception if unable to do so.
*
* #return computed result
* #throws Exception if unable to compute a result
*/
public String call() throws Exception {
insertEmployee(employee);
return "SUCCESS";
}
}
In other class you can use the ExecutorService like below
try{
Set<Callable<String>> callables = new HashSet<Callable<String>>();
EmployeeDTO employee = new EmployeeDTO(emp);
callables.add(employee);
ExecutorService executorService = Executors.newFixedThreadPool(1);
List<Future<String>> futures = executorService.invokeAll(callables);
}catch (ExecutionException eEx) {
eEx.getMessage();
}finally{
executorService.shutdown();
}
Hello all i have write this servlet to doGet data and Client-side can get some information from database after query and
pointer but when i send a pointer to servlet from client-side there
are no response and http code is 204 can any one help me with that?
thanks
//This Servlet Make User To Get Data from Database (data) Table (replay) Fileds (Callreplay,State)
package server;
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(name = "GetStatus", urlPatterns = {"/GetStatus"})
public class GetStatus extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetStatus()
{
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// getting id as parameter
String strID;
strID = request.getParameter("newid");
System.out.println("* Pointer is "+strID);
// connecting to the database
GetStatusFromDB dbManager = new GetStatusFromDB();
dbManager.iniDBManagementLayer("jdbc:mysql://127.0.0.1:3306/data",
"root",
""
);
//System.out.println("** Connection with database OK!");
// getting data from the database
String sql = "SELECT * FROM replay WHERE S_id = " + strID + ";";
dbManager.setFields("status", "comment");
dbManager.sendQuery(sql);
String resp = dbManager.getJSON();
System.out.println("*** Mutaz Method Ok!");
if(resp != null)
{
System.out.println(resp);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=utf-8");
response.getWriter().print(resp);
// System.out.println("Get Ok !");
}
else
{
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
public void sendQuery(String query) {
// Connection, statement, and ResultSet should not defined as instances
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/jndipool");
conn = ds.getConnection();
st = conn.prepareStatement(query);
rs = st.executeQuery();
processResults(rs);
} catch (NamingException ex) {
// Logger.getLogger(DBManagementLayer.class.getName()).log(Level.SEVERE, null, ex);
this.errorFlag = true;
this.lastError = ex.toString();
} catch (SQLException ex) {
this.errorFlag = true;
this.lastError = ex.toString();
}
finally{
if ( rs != null ) {
try { rs.close(); rs = null;}
catch (SQLException e) {
errorFlag = true; lastError = e.toString(); }
}
Http response code 204 is what is being set by this line
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
So it's likely that dbManager.getJSON() is returning null.
**in this line i most add
try
{
////here most add rs.first();
Gson conv = new Gson();
String status = rs.getString(fieldOne);
String comment = rs.getString(fieldTwo);
String rep = conv.toJson(new StatusForm(status, comment ));
this.statusAsJSON = rep;
} catch (SQLException ex) {
Logger.getLogger(GetStatusFromDB.class.getName()).log(Level.SEVERE, null, ex);
}
this must add
boolean first = rs.first();
and it will be fixed
thanks for evrey body here help me thanks for all programmers here thank you stackoberflow.com Max**
I am trying to make a simple login form. Every thing is working fine, connection is established, query is executed but ResultSet is still empty so always getting redirected to fail.jsp. No error no warning at all.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
modelclass md = new modelclass();
daoclass dao = new daoclass();
md.setName(name);
md.setPassword(password);
System.out.println("this just before the sql query on the main servlet page");
String sql = "Select * from USERADD where name = ? and password= ?";
String result = dao.guser(md, sql);
if (result.equals("success")) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("fail.jsp");
}
}
This is the DAO class which makes connection.
Data Access code(dao.java):
public class daoclass {
public static String username = "NickNeo";
public static String password = "123123";
public static String driver = "com.ibm.db2.jcc.DB2Driver";
public static String url = "jdbc:db2://localhost:50000/CITYLIFE";
public static Connection con = null;
public static PreparedStatement ps = null;
static {
try {
Class.forName(driver);
System.out.println("before connection");
con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Successfullll......!!!!!!");
} catch(Exception e) {
e.printStackTrace();
}
}
public String guser(modelclass obj, String sql) {
try {
System.out.println("entry into try block");
ps=con.prepareStatement(sql);
ps.setString(1, obj.getName());
ps.setString(2, obj.getPassword());
System.out.println("before query");
ResultSet rs = ps.executeQuery();
System.out.println("query executed");
int i = 0;
while(rs.next()) {
System.out.println("entered into while loop");
++i;
}
if (i >= 1) {
return "success";
} else {
System.out.println("this is inside else of while block");
return "fail";
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("this is the most outer fail statement");
return "fail";
}
}
the rs is always empty. tried many things but still getting rs as empty. please help
I would like to have a database connection managing class which I can use for simple SQL commands like SELECT, INSERT etc. by simple calling something like this (class below):
ResultSet test = DataService.getResultSet("SELECT NOW()");
test.first();
System.out.println(test.getString(1));
This is class I've found on web:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Database object to load drivers and perform queries
* #author Abdulsalam Umar blog.salamtura.com
*/
public class DataService {
private static Connection con;
private static final String Driver = "oracle.jdbc.driver.OracleDriver";
private static final String ConnectionString = "Your database connection string";
private static final String user = "username";
private static final String pwd = "password";
/**
* create Database object
*/
public DataService() {
}
/**
* to load the database base driver
* #return a database connection
* #throws SQLException throws an exception if an error occurs
*/
public static Connection loadDriver() throws SQLException {
try {
Class.forName(Driver);
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
con = DriverManager.getConnection(ConnectionString, user, pwd);
return con;
}
/**
* to get a result set of a query
* #param query custom query
* #return a result set of custom query
* #throws SQLException throws an exception if an error occurs
*/
public static ResultSet getResultSet(String query) throws SQLException {
Connection con = loadDriver();
ResultSet rs;
PreparedStatement st = con.prepareStatement(query);
rs = st.executeQuery();
return rs;
}
/**
* to run an update query such as update, delete
* #param query custom query
* #throws SQLException throws an exception if an error occurs
*/
public static void runQuery(String query) throws SQLException {
Connection con = loadDriver();
ResultSet rs;
PreparedStatement st = con.prepareStatement(query);
st.executeUpdate();
}
}
Is this way of returning ResultSet without closing it (and closing the statement) right? How can I return the ResultSet from the method?
Returning result set is not a good idea. So,fetch the required data and make use of collection to return the data.
This answer may be useful
How about passing a callback that takes ResultSet as parameter and let client code do whatever needs to inside it while you make sure that everything is cleaned up afterwards.
This is pattern in used in spring JDBC ResultSetExtractor and RowMapper. Look at this answer.
You can't return ResultSet because it will be closed when method destroyed. But you can get raw data from ResultSet, try this:
public ArrayList<ArrayList<byte[]>> getResultQuery(String query){
ArrayList<ArrayList<byte[]>> tableResult = new ArrayList<>();
ArrayList<byte[]> row;
conn = getConnection(db_url);
try {
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(query);
int countColumn = resultSet.getMetaData().getColumnCount();
if (countColumn==0) return null;
while (resultSet.next()){
row = new ArrayList<>();
for (int i = 0; i<countColumn; i++){
row.add(i,resultSet.getBytes(i+1));
}
tableResult.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tableResult;
}
public static Connection getConnection (String db_url){
Connection conn = null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(db_url);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
In this, i try to return ArrayList of ArrayList<byte[]>, ArrayList<byte[]> = 1 row in ResultSet. If you want to get some value, just use row.get(i) to get value from column i+1 in ResultSet which look like a 2 dimensions Matrix
I have a null pointer exception in
ResultSet rs = aStatement.executeQuery(Query); // it can't be executed
my code is like this :
public static boolean testLogin(String user, String password) throws SQLException {
String Query = "select * from TBL_Users where userName = '" + user + "' and passWord = '" + password + "' ";
ResultSet rs = aStatement.executeQuery(Query);
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true;
}
return false;
}
}
Most likely aStatement is null.
Sounds like you think aStatement should not be null, but it is.
This is bad JDBC code, for many reasons:
No cleanup of resources.
Doesn't use PreparedStatement
Keeps creating the query string over and over again instead of using a static variable
Doesn't follow Java coding standards ("Query" should be "query")
Here's another way to write it. Start with an interface:
package persistence;
import java.sql.SQLException;
public interface CredentialDao
{
boolean isValidUser(String username, String password) throws SQLException;
}
Write an implementation:
package persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CredentialDaoImpl implements CredentialDao
{
private static final String CREDENTIAL_QUERY = "SELECT COUNT() FROM USER WHERE USERNAME = ? AND PASSWORD = ?";
private Connection connection;
public CredentialDaoImpl(Connection connection)
{
this.connection = connection;
}
public boolean isValidUser(String username, String password) throws SQLException
{
boolean isValidUser = false;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = this.connection.prepareStatement(CREDENTIAL_QUERY);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
while (rs.next())
{
int count = rs.getInt(1);
isValidUser = (count > 0);
}
}
finally
{
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return isValidUser;
}
}
The aStatement variable is apparently null, please validate that it is correctly set. You should consider read the Java Naming Conventions and make sure you use the lower camel case for variables and java bean conventions.
For code snippets in stackoverflow if they are not self-explanatory, you should obey the rules of the SSCCE, this will help you to get more and better answers. Also you should provide a stack trace with the occured exception.
Use prepared statements.
Connection con = ...; // obtain connection here
PreparedStatement pstmt = con.prepareStatement("select * from TBL_Users where userName = ?'");
pstmt.setInt(1, userName);
ResultSet rs = pstmt .executeQuery();
...
// do clean up here
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true; // Huh? What?
}
What is info refering to and why is there a return imediatly after the assignments?