T
T
The_XXI2021-04-14 17:29:30
Java
The_XXI, 2021-04-14 17:29:30

Why can't I call a static method from another class?

There are 2 classes. They are in the same package.
DBHandler class:

package utils;

import java.sql.*;

public class DBHandler {

    static Connection connection;

    public static boolean openConnection() {
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demotest", "root", "");
            return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

    public static boolean closeConnection() {
        try {
            connection.close();
            return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

    public static ResultSet executeQuery (String sql) {
        ResultSet resultSet = null;
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            if (sql.contains("SELECT")) {
                resultSet = preparedStatement.executeQuery();
            } else {
                preparedStatement.executeUpdate();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();

        }
        return resultSet;

    }
}

The second class is completely empty and in it I try to call openConnection:
package utils;

public class ClientTable {
    DBHandler.openConnection();
}

It throws an error
C:\Users\mk_11\IdeaProjects\AutoService002\src\utils\ClientTable.java:4:29
java: <identifier> expected

What is the problem?
When calling openConnection from other classes in other packages, everything works.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-04-14
@The_XXI

package utils;

public class ClientTable {
    DBHandler.openConnection();
}

Well, you must have a method inside which you will call the openConnection () method.
For example,
package utils;

public class ClientTable {
    
private void call() {
DBHandler.openConnection();
}

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question