I'm trying to make a method that retrieves a customer from a database and stores it in an object. But for some reason my sql statement is not working.
This is my method.
public class CustomerDAO {
private String url = "jdbc:h2:tcp://localhost/project;IFEXISTS=TRUE";
Set<Customer> customerCollection = new TreeSet<>();
public Customer loginCustomer(String user,String pass) throws SQLException{
String sql = "SELECT * FROM Customers WHERE USERNAME=(?) AND PASSWORD=(?) ;";
try(
//get connection form database
Connection dbCon = JdbcConnection.getConnection(url);
//create a statement
PreparedStatement stmt = dbCon.prepareStatement(sql);
){
stmt.setString(1, user);
stmt.setString(2, pass);
ResultSet rs = stmt.executeQuery();
Customer c = new Customer(rs.getString("username"), rs.getString("name"), rs.getString("email"),
rs.getString("address"), rs.getString("creditCardDetails"), rs.getString("password"));
if(c.getUsername().contains(user))
return c;
else
return null;
}catch (SQLException ex){
throw new RuntimeException(ex);
}
}
I tested it using this
public static void main(String[] args) throws SQLException {
CustomerDAO dao = new CustomerDAO();
Customer c = dao.loginCustomer("jesus", "1234");
System.out.println(c.getName());
System.out.println(c.getPassword());
System.out.println(c.getAddress());
}
}
but i get these errors.
Exception in thread "main" java.lang.RuntimeException: org.h2.jdbc.JdbcSQLException: No data is available [2000-187]
at DAO.CustomerDAO.loginCustomer(CustomerDAO.java:54)
at web.NewMain.main(NewMain.java:25)
Caused by: org.h2.jdbc.JdbcSQLException: No data is available [2000-187]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.message.DbException.get(DbException.java:144)
at org.h2.jdbc.JdbcResultSet.checkOnValidRow(JdbcResultSet.java:3186)
at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:3192)
at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:3209)
at org.h2.jdbc.JdbcResultSet.getString(JdbcResultSet.java:302)
at DAO.CustomerDAO.loginCustomer(CustomerDAO.java:43)
... 1 more
Java Result: 1
Running the statement directly from the database console works fine. for example
SELECT * FROM Customers WHERE USERNAME='jesus' AND PASSWORD='1234' ;