0

I am having the below problem with the code.

I get a NullPointerException when I try to connect and get data from the database. I get the error when the executeQuery is carried out I think. As far as I know the code is correct but the way to connect to the database as sys is still something I am not sure about.

here goes:

package masterdocument;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
import java.lang.*;
import oracle.jdbc.driver.*;
public class JavaConnectDB {
public static Connection ConnecrDB(){
try{
    String driverName = "oracle.jdbc.driver.OracleDriver";
    Class.forName(driverName).newInstance();
    String nameForConnect = "sys as sysdba";
    String pass = "Abcd1234";
    String url = "jdbc:oracle:thin:@localhost:1521:db01";
    Connection conn = DriverManager.getConnection(url, nameForConnect, pass);
    System.out.println(conn);
    return conn;
    }
catch (Exception e){
    JOptionPane.showMessageDialog(null,e);
    return null;
    }    
 }
}

and the call to the connection above:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)         {                                         

conn = JavaConnectDB.ConnecrDB();
        try{
            String sql="select * from TUTILIZADORES where USERNAME=? and PASSWORD=?";
        pst.setString(1, USERNAME.getText());
        pst.setString(2, PASSWORD.getText());
        rs=(OracleResultSet)pst.executeQuery();
        if (rs.next()){
        JOptionPane.showMessageDialog(null, "O username e password estavam bem");

        Tutilizadores c = new Tutilizadores();
        c.setVisible(true);
        }
        else{
        JOptionPane.showMessageDialog(null, "Login Inválido");
        }

    } catch(Exception e){
                        JOptionPane.showMessageDialog(null,e);
                        }       
}      

I am somewhat new to Java.

Thank you.

unknown
  • 4,859
  • 10
  • 44
  • 62
AlexG
  • 11
  • 5

1 Answers1

0

You're probably missing the part that creates the PreparedStatement:

String sql="select * from TUTILIZADORES where USERNAME=? and PASSWORD=?";
pst = conn.prepareStatement(sql);

You should also make sure to close this statement and the ResultSet after finishing with using them. You can do this in a finally block:

} catch(Exception e) {
     JOptionPane.showMessageDialog(null ,e);
} finally {
   if(rs != null) {
       rs.close();
   }
   if(pst != null) {
       pst.close();
   }
}
M A
  • 71,713
  • 13
  • 134
  • 174
  • I have used Connection conn=null; OraclePreparedStatement pst=null; OracleResultSet rs=null; – AlexG May 24 '15 at 18:52
  • @AlexG See http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it. – M A May 24 '15 at 18:56
  • I have added : PreparedStatement pst = conn.prepareStatement(sql); and its working. Thank you Manouti!! – AlexG May 24 '15 at 19:27