-1

I ran in to a problem while trying to get data from my sql server where they give a null point exception at prepared statement. I'm sure this must be a noob question but please do help :)

this is the method i'm calling

public void notification(){
    int MachCode = 1721;
    try{
        String sql ="Select TimeOn from PRODUCTIONS_MONITOR where MachCode='"+MachCode+"'";
        pst = con.prepareStatement(sql);
        rs = pst.executeQuery();

        while(rs.next()){
            arrCount.add(rs.getInt(1));

        }

        for(int i=0;i<arrCount.size();i++){

             Count = Count + arrCount.get(i);

        }

        if(Count % 10 == 0){

            System.out.println("Time = " + Count);

        }

    }catch(SQLException e){

        e.printStackTrace();

    }

}

and here is my db connection

  public static Connection ConnecrDb() {
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 

       Connection con = DriverManager.getConnection("jdbc:sqlserver://10.228.59.2:1433;databaseName=dbNautilus;user=SA;password=KreedaIntimo@2017;");

        System.out.println("Connected to database !");

    } catch (SQLException sqle) {
        System.out.println("Sql Exception :" + sqle.getMessage());
    } catch (ClassNotFoundException e) {
        System.out.println("Class Not Found Exception :" + e.getMessage());
    }

    return null;
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

2

Your ConnecrDb() method assigns the new Connection object to a local variable named con, and then never use it.

The method then returns null.

You didn't show how to method was called, but it really doesn't matter, because the con field used by notification() method is either unassigned (and hence null), or assigned the null return value from ConnecrDb(), so it is null either way.

Given that, why are you confused the value is null and causes a NullPointerException?


Other general comment about your code:

  • If MachCode is an integer, then why are you quoting it in SQL, i.e. why where MachCode='"+MachCode+"'"; and not where MachCode="+MachCode;?

  • If you're using PreparedStatement, why not use ? parameter markers, as they are intended to be used?

  • You should use try-with-resources when using JDBC.

  • Java naming convention is for variable names to start with lowercase letter.

Your code should be:

int machCode = 1721;
String sql = "select TimeOn from PRODUCTIONS_MONITOR where MachCode = ?";
try (PreparedStatement pst = con.prepareStatement(sql)) {
    pst.setInt(1, machCode);
    try (ResultSet rs = pst.executeQuery()) {
        while (rs.next()) {
            arrCount.add(rs.getInt(1));
        }
    }
}
// rest of code here
Andreas
  • 154,647
  • 11
  • 152
  • 247