Stephan van Hulst wrote:The code is not absolutely right. You're calling prepareStatement() on conn, a local variable that was initialized as null.
Try not to hide fields in methods other than setters. Don't pull resources out of thin air (the static getConnection() method). Pass dependencies as method/constructor parameters. Use the return values of method calls (c.getConnection() is discarded). Don't call static methods on references to objects. Don't mix the presentation layer with the persistence layer: Don't access the database from an action listener. Use DataSource instead of a custom connection manager class.
Stephan van Hulst wrote:If you only removed those parts of the code, your code wouldn't compile because you're accessing an uninitialized local variable.
Please post the entire method, and the new compiler error and exception message that you're getting.
Stephan van Hulst wrote:It doesn't. PreparedStatement has nothing to do with it. A NullPointerException happens when you try to dereference null. The only thing you're dereferencing on that line is conn, meaning conn is null.
You're never actually setting the value of conn to something other than null. The reason that you're running into this problem in such an unexpected place is because you're not injecting your dependencies through constructor or method parameters, and you're not performing parameter checking.
Dave Tolls wrote:
This returns a Connection object.
You are doing nothing with that Connection object and are, instead, using the null reference 'conn' instead.
Dave Tolls wrote:
Indeed, you need to be closing these things off, otherwise you will end up with a resource leak (you'll run out of connections to the db for example).
So the above ought to be:
Similarly with the PreparedStatement.
omar tawfeek wrote:
thank you so much this method worked for me