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='?'");


上面是我的代码片段。我将ConnectionResultset对象声明为静态,以便可以从静态验证程序方法中调用它们。
验证器方法也声明为静态,因此仅使用className.verificator(param,param)就可以从其他类中将其作为类变量进行调用。

当我单独测试该类时,它将编译并运行,但是每当从不同的类进行调用时,我都会在PerparedStatement行中收到NullPointerException错误。

有人可以帮我为什么会发生吗?

谢谢

最佳答案

您说过,您将verifyator方法声明为静态的,因此可以从其他类中访问它,并且verificator方法使用的连接也是静态的。

问题在于连接仅在对象的构造函数中初始化,因此,如果从不调用构造函数,connect将为null。

您需要在静态块中初始化connect变量,或者在使用前验证它是否为null。

09-10 20:56
查看更多