0

The problem is that NullPointException occurs at st = con.createStatement(); rs = st.executeQuery("select * from noit"); rs.next(); but they are declared to be null. The first code is for connection to MySQL and the second is to give a function to a button.

public class database {
    public void con(){
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;
    String nqkuvsi = null;
    try{
        con = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogin","root","1234");       
        if(con!=null){
            System.out.println("successfull");
           }}catch(Exception e){
        System.out.println("no connection");
        e.printStackTrace();
    }
}
}    

connection answers "successful"

public void actionPerformed(ActionEvent a){
db.con();    
    ResultSet res = null;       
    int resul = 0;
    Object s = a.getSource();           
    if(s==jbut){
     Random rand = new Random();
        Random rand1 = new Random();
             int rnd = rand.nextInt(2)+1;           
             int rnd1 = rand1.nextInt(2) + 2;
         String nqkuv = null;
         String nqkuv1 = null,nqkuv2 = null,nqkuv3 = null;
         if(rnd==1){                 
             try{               
             st = con.createStatement();
             rs = st.executeQuery("select * from noit");
             rs.next();
             nqkuv = rs.getString(rnd1);
         }catch(SQLException e){
             e.printStackTrace();
         }
fanten27
  • 11
  • 2
  • I think you have a scope problem. Obviously in `st = con.createStatement();` con is null so debug it or paste the full code here. – theo Jan 09 '16 at 17:20
  • The scope of the `con` variable that you initialize is limited to the `con()` method. The `con` variable used in the `actionPerformed(...)` is probably some other variable that was never initialized (is `null`). – Titus Jan 09 '16 at 17:20
  • i've tried but nothing worked – fanten27 Jan 09 '16 at 17:33

0 Answers0