public static Connection connect;
public static ResultSet resultSet;
static final String DATABASE_URL = "jdbc:mysql://localhost/java_dev";
public ServerFunctions() {
String Driver = "com.mysql.jdbc.Driver";
String DB_USERNAME = "lucky";
String DB_PASSWORD = "lucky";
try {
Class.forName(Driver);
connect = DriverManager.getConnection(DATABASE_URL,DB_USERNAME, DB_PASSWORD);
} catch(Exception e) {
System.out.println("Database Not Connected ! ");
}
}
public static Boolean verificator(String username, String password) {
try {
PreparedStatement prepare = connect.prepareStatement(
"Select * from users where username='?'&&password='?'");
Above is my code fragment. I am declaring the Connection and Resultset objects static so they can be called from the static verificator method.
also the verificator method is declared static so that it can be called from a different class as class variable just by using className.verificator(param, param).
It compiles and run when I test the class alone but then i get the NullPointerException error at the PerparedStatement Line whenever a call is made from different class.
Can someone Please help me why it is Happening ?
Thankyou
You said you declared the verificator method as static, so it can be accessed from other classes, and the verificator method is using the connection, which is also static.
The problem is that the connection is only initialized in the constructor of the object, so, if the constructor is never called, connect will be null.
You need to either initilize your connect variable in a static block, or verify if it is null before using it.