Duncan Palmer
Duncan Palmer

Reputation: 2913

Java MYSQL Nullpointerexception

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

Upvotes: 0

Views: 4920

Answers (2)

Duncan Palmer
Duncan Palmer

Reputation: 2913

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

Upvotes: 0

Icarus
Icarus

Reputation: 63956

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.

Upvotes: 3

Related Questions