<<< static Initialization Block, cont. | Index | static and instance variables/methods >>> |
A better alternative to the static initialization block is simply to use a static method:
public class className
{
// any field declarations
private static DBConnection connection = initializeConnection();
private static DBConnection initializeConnection() {
{
DBConnection connection = null;
try {
String url = "jdbc:mysql://localhost:3306/SampleDB";
String user = "robert";
String password = "secret";
connection = DBDriverManager.getConnection(
url, user, password
);
} catch (Exception ex) {
System.err.println(
"Error: unable to connect to the database."
);
}
return connection;
}
// the rest of the class
}
<<< static Initialization Block, cont. | Index | static and instance variables/methods >>> |