title: When my app loses connection, how should I recover it?
body: <p>I have an app that I'm connecting to a MySQL database. It loses connection in the middle of the night and then spouts about <code>null</code> connections and JDBC hasn't received messages in X seconds.</p>
  
  <p>I call <code>getConnection()</code> before I do anything that requires communication with the SQL server.</p>
  
  <p>This is my <code>getConnection()</code> method:</p>
  
  <pre><code>private Connection getConnection() {
      try {
          if (connection != null) {
              if (connection.isClosed() || !connection.isValid(10000)) {
                  this.initializeRamsesConnection();
              }
          } else {
              this.initializeRamsesConnection();
          }
      } catch (Exception e) {
          debug("Connection failed: " + e);
      }
      return connection;
  }
  </code></pre>
  
  <p>In the <code>initializeRamsesConnection()</code> method I put the password and so on information into a string and then I create the connection in the standard JDBC way.</p>
  
  <p>Then I call this method:</p>
  
  <pre><code>private Connection getConnectionFromConnectionString() {
      Connection con = null;
      String driver = "com.mysql.jdbc.Driver";
      try {
          Class.forName(driver);//jdbc sorcery
          //if there is no connection string
          if (getConnectionString() == null) {
              HMIDatabaseAdapter.debug("No connection string");
          }
          //makes a string out of the values of db/host
          String str = getConnectionString();
          //if there is no driver
          if (driver == null) {
              debug("" + ": " + "No driver");
          }
          //Tries to make a connection from the connection string, username, and the password.
          con = DriverManager.getConnection(str, username, password);
          //if for some reason the connection is null
          if (con == null) {
              HMIDatabaseAdapter.debug("CONNECTION IS NULL, WHAT?");
          }
      } catch (Exception ex) {
          HMIDatabaseAdapter.debug("getConnection() " + ex);
      }
      return con;
  }
  </code></pre>
  
  <p>What can I change in either of these methods to accommodate losing connection?</p>