Adnan Ahmad Khan
Adnan Ahmad Khan

Reputation: 644

Null Pointer Exception in Method Which Sets the Parameters for Prepared Statement

I Have Looke over the internet that from Last 12 hours , and found that too many Users are facing that Problem , But None of them are Able to get Rid of That, I hav Created a JDialog , Which have TextFields, and i am Trying to get Input From those text Fields, and Store That In DataBase, But is Givi the Following Exception.

Exception occurred during event dispatching:
Connection ok
Adnan
java.lang.NullPointerException
at srvrDataBaseClass.setPersonStatement(srvrDataBaseClass.java:90)
at srvrDataBaseClass.insertPerson(srvrDataBaseClass.java:71)
at EnrollmentForm.setPerson(EnrollmentForm.java:90)

Here is the Code Where the StackTrac is Pointing ,

public void setPersonStatement(String nm,String fn,String cn,String add, byte[] fpt) {
    String Sql = "INSERT INTO PERSON (NAME, FNAME, CNIC, ADDR, FPT) VALUES ( ?,?,?,?,?)";
    try {
        if(con==null){
            System.out.println("Connection error");   <---------------- Connection is Not Closed
        }
        else {
            System.out.println("Connection ok");    <------Connection ok
        }


        con.prepareStatement(Sql);

    System.out.println(nm);     <----- This is Line :90,  But You can see its not Null, as the Value 'Adnan' is printed on cmd,
    pst2.setString(1, nm);
    pst2.setString(2, fn);
    pst2.setString(3, cn);
    pst2.setString(4, add);
    pst2.setBytes(5, fpt);

    pst2.executeUpdate();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        System.out.println("SQL Error");
        e.printStackTrace();
    }
    }

So Any One Who can tell me , Whats Wrong with my Code

Note: DataBase is SQL Server 2008,

Upvotes: 1

Views: 1485

Answers (2)

user3197426
user3197426

Reputation: 13

con.prepareStatement(Sql);

is not assigned to a proper PreparedStatement Variable,

write as

pst2= con.prepareStatement(Sql);

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279930

Did you mean to do

pst2 = con.prepareStatement(Sql);

? It seems like pst2 is null and will remain so in

pst2.setString(1, nm);

which probably actually throws the NPE.

Check out the javadoc for the method you are trying to use.

Upvotes: 5

Related Questions