andveand
andveand

Reputation: 481

java.lang.NullPointerException** error?

I am trying to add records to Sql Server in Java. In this function, program gives an error like that:

Connected
1
2
Error java.lang.NullPointerException

It is the output..

Function is below:

public class DB {

    Connection con = null;
    Statement stmt Nnull ;
    component cmp = new Component();

    public long pSave(Component cmp) {
        String i = cmp.getI();
        String s = cmp.getS();
        String a = cmp.getA();
        int t = cmp.getT();
        int c = cmp.getC();

        System.out.println("1");

        try {
            System.out.println("2");
            stmt = con.createStatement();

            System.out.println("3");
            String SQL =
                "INSERT INTO kisi (cl1,cl2,cl3,cl4,cl5) "
                + "VALUES(" + i + "," + s + "," + a + "," + c + "," + t + ")";

            System.out.println("4");
            stmt.executeUpdate(SQL);

            System.out.println("Success");

            return 1;
        } catch(Exception e) {
            System.out.println("Error " + e);
            return 0;
        }
    }

}

Upvotes: 0

Views: 11218

Answers (5)

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

A little bit of debugging may help.

You may notice your output says Connected 1 2 Error java.lang.NullPointerException. The 1 and 2 suggest that you reached the first and second println statements and the Error NPE suggests that a line of code after those failed. The third println is never hit, which means your NPE happened between 2 and 3. There exists a single statement between these two, and that is where you are getting your NPE.

So the question now is, what could be causing the NPE? I will leave that as an exercise for the reader. :)

Upvotes: 0

Oleg Mikheev
Oleg Mikheev

Reputation: 17444

NullPointerException means that you're trying to call a method on a null object. That null object is your con that you never initialize. You should add these two lines to initialize it:

Driver d = (Driver)Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:microsoft:sqlserver://server:1433", "userName", "password");

Upvotes: 4

AlexR
AlexR

Reputation: 115328

Connection con = null;
......
stmt = con.createStatement();
        ^

The connection is not initialized. You have to connect to DB in order to retrieve data.

Upvotes: 4

Rob
Rob

Reputation: 4947

You didnt initialize the connection con which you are calling when you're trying to initialize the statement.. stmt = con.createstatement

Upvotes: 2

Mechkov
Mechkov

Reputation: 4324

You need to create a Connection object first. You have: Connection con = null;

So, you cant create a statement from a connection that is null.

Upvotes: 2

Related Questions