0

I am currently using a number of static methods within a class to read data from a MySQL database. The following code is an example of one of these methods:

DatabaseReader Class:

public class DatabaseReader
{
    //Method to get an employee's details.
    public static JSONArray getEmployee(String employeeID)
    {
        String query = "SELECT * FROM employee WHERE employeeID = ?";
        DatabaseConnection dbc = new DatabaseConnection(query);
        dbc.setString(1, employeeID);
        return getResultsFromQuery(dbc);
    }

    //More static methods here...
    //...
    //...
}

So to call this method, I use the DatabaseReader.getEmployee(employeeID); statement within my code.

Based on the above, I understand that the getEmployee() method belongs to the DatabaseReader class instead of belonging to an instance of it (e.g. DatabaseReader dbr = new DatabaseReader(); followed by dbr.getEmployee(1);).

I am not sure though if it is good practice to use static methods for database connectivity, since there will be multiple users using the same methods.

If there are two users using the getEmployee() method, would the query and dbc variables within the static method be static as well, and thus shared across both of these users? Or would each of these users be using their own separate instances of a query String and dbc DatabaseConnection?

Is it reasonable to use static methods (such as the one above) for reading/writing to a database?

3
  • see this answer especially the comments May 2, 2017 at 1:25
  • What do you mean users? Methods aren't called by people, they're called by other methods.
    – user253751
    May 2, 2017 at 1:58
  • If two "users" call a non-static method do they share the same local variables? No they don't.
    – user253751
    May 2, 2017 at 2:00

1 Answer 1

0

"No, it's not a static variable. It's a local variable. Any variable declared in a method is a local variable." -Source: In Java, are variables declared inside static methods themselves static?

I think you're fine using static methods for database connections. I might encourage it in fact.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.