title: Best way to open and return a database connection in a Java application?
body: <p>I have come up with the following utility class:</p>
  
  <pre><code>import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.SQLException;
  
  public class MySqlConnection
  {
      private static String dbUrl = "jdbc:mysql://localhost:3306/database";
      private static String dbUsername = "root";
      private static String dbPassword = "mysql";
  
      public static Connection getConnection()
      {
          Connection connection = null;
          try {
              Class.forName("com.mysql.jdbc.Driver");
              connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
          } catch (ClassNotFoundException e) {
              System.out.println("Could not load JDBC driver: " + e.getMessage());
          } catch (SQLException e) {
              System.out.println("Could not connect to DB: " + e.getMessage());
          }
          return connection;
      }
  }
  </code></pre>
  
  <p>The problem is: <strong>I do not want to return <em>null</em> from my method</strong>, because by doing so I force my callers to do a <code>if (connection != null) {...}</code> check every time they open and want to use a connection. I find these null checks to be error prone and want to avoid them at all costs. What other approach could I follow to manage database connections in my application?</p>