Sani Aliyu
Sani Aliyu

Reputation: 1

Working with Java database

I'm creating a java program which requires a user to provide login details before gaining access. i'm working with a javaDB which i stored the data in a table named LOGIN_DETAILS, i have a successful connection but the problem is whenever i run the program i get this error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Classes.Login.bActionPerformed(Login.java:188)

and login.java:188 code is: Statement st = con.createStatement();

Below is my complete code;

    public void connect(){
        try{
        String host = "jdbc:derby://localhost:1527/db1";
        String uName = "";
        String uPass = "";
        con = DriverManager.getConnection(host, uName, uPass);

        }

        catch(SQLException ex){
    }

}

    try{

    Statement st = con.createStatement();
    Menu MM = new Menu();
    String user = t.getText().trim();
    String pass = t1.getText().trim();

    String sql = "SELECT USERNAME, PASSWORD FROM "
            + "APP.LOGIN_DETAILS WHERE "
            + "USERNAME ='"+user+"'PASSWORD ='"+pass+"'";
    ResultSet rs = st.executeQuery(sql);

    int count = 0;
    while(rs.next()){
        count = count + 1;
    }

    if(count ==1){
    JOptionPane.showMessageDialog(null, "User Found, Access Granted");
    this.dispose();
    MM.setVisible(true);
    }

    else if(count > 1){
    JOptionPane.showConfirmDialog(null, "Duplicate User, Access Denied");
    this.setVisible(true);
    }
    else{
    JOptionPane.showMessageDialog(null,"User not Found");
    this.setVisible(true);
    }
    }

    catch(SQLException | HeadlessException ex){
    }

Please help me in resolving the problem, thank you.

Upvotes: 0

Views: 99

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44814

con is very likely to be null in this situation properbably due to connect() not being called. Although, maybe connect() is being called and there is a SQLException exception which is silently being caught. In most cases, it is a bad idea to catch an exception and do nothing about it. Minimally, you should log the exception.

Also this is incorrect

String sql = "SELECT USERNAME, PASSWORD FROM "
        + "APP.LOGIN_DETAILS WHERE "
        + "USERNAME ='"+user+"'PASSWORD ='"+pass+"'";

try

String sql = "SELECT USERNAME, PASSWORD FROM "
        + "APP.LOGIN_DETAILS WHERE "
        + "USERNAME = '" +user+ " and 'PASSWORD ='"+pass+"'";

Upvotes: 0

seanoftime
seanoftime

Reputation: 186

Unless this bit of code appears elsewhere, it appears that you have not called the connect() method (which sets up the connection) before calling createStatement() on con. Thus, con likely still points to null at that point. If that's the case, it would explain the exception.

Upvotes: 1

Related Questions