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?

dat3450
  • 954
  • 3
  • 13
  • 27

1 Answers1

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.

Community
  • 1
  • 1
Glen Pierce
  • 4,401
  • 5
  • 31
  • 50