title: How should I connect to JDBC database / datasource in a servlet based application?
body: <p>I have an external MySQL server that's set up and working fine.  I created a database connection in Eclipse and can view the database in the Data Source Explorer tab.</p>
  
  <p>Now, I have a servlet that needs to access that database.  How do I do it?  Is there a way to reference that database connection created in the data source explorer, or do I have to define everything twice?</p>
  
  <p>Also, what's the best way to open the connection?  I've got the <code>mysql-connector-java-5.1.11-bin.jar</code> file included, and I've found two methods that work:</p>
  
  <pre><code>MysqlDataSource d = new MysqlDataSource();
  d.setUser("user");
  d.setPassword("pass");
  d.setServerName("hostname.com");
  d.setDatabaseName("db");
  Connection c = d.getConnection();
  </code></pre>
  
  <p>and</p>
  
  <pre><code>Connection c = DriverManager.getConnection("jdbc:mysql://hostname.com/db","user","pass");
  </code></pre>
  
  <p>Neither is optimal, because first of all, they both use hard-coded strings for everything.  This is a Java EE web app project, so is there a good place to put connection data?  Or is there a way to forgo all that and just use the connection in the data source explorer?</p>