0

Hey guys i'm trying to connect to my database and run a query. it all works apart from the query execution (after narrowing it down i found it to be this) Below i my code:

              Statement statement = null;
          ResultSet result;

           result = statement.executeQuery(query);//this is where error is being caused

           while(result.next())
           {
               Print("ID: " + result.getString("id"));
               Print("USER: " + result.getString("username"));
               Print("PASS: " + result.getString("password"));
           }

I get this returned:

database!java.lang.NullPointerException

Thanks for any help you give me

2

2 Answers 2

3

The query looks right. Surely the statement variable is NULL and you are trying to call executeQuery.

UPDATE:

Try this:

Statement statement = conn.createStatement ();

where conn is a Connection object. I'm sure you have one of those objects somewhere in your code.

Sign up to request clarification or add additional context in comments.

4 Comments

You updated your question after I posted my answer. I'm glad I guessed. doing statement =null; and right after statement.executeQuery(); is obvious that will throw a nullpointerexception.
No, the opposite: It will never work! You are setting statement to NULL! You have to create an instance of statement before you can call any methods.
@Icarus how would i get it to work then? If i don't it throws an error saying I need to Initialize the variable.
@DuncanPalmer Set the statement variable to something other than null.
0

Fixed my problem by using a prepared statement:

           String query = "SELECT * FROM users";

          PreparedStatement statement = null;
          ResultSet result;
          statement  = conn.prepareStatement(query);
          result = statement.executeQuery(query);

           while(result.next())
           {
               Print("ID: " + result.getString("id"));
               Print("USER: " + result.getString("username"));
               Print("PASS: " + result.getString("password"));
           }

Thanks for your help

1 Comment

You're specifying the query twice so the preparedness of it isn't used. result=statement.executeQuery() will do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.