Connect to a MySql datasource in java

By | July 15, 2012

Instead of using the old DriverManager its the better way to use the DataSource class to get a connection to a MySql Database. This can be done by geting it from the app server container or by creating and configuration it directly from the driver.

Get the MySQL datasource from the app container

Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");

Create the datasource instance

MysqlDataSource ds= new MysqlDataSource(); 
ds.setServerName("host.domain.de"); 
ds.setUser("user"); 
ds.setPassword("secret");

When you got the datasource you can use it to get connection out of it which can be used as usual.

Connection conn = dataSource.getConnection(); 
Statement stmt = conn.createStatement(); 
ResultSet rs = stmt.executeQuery("MY QUERY"); 
 
... 
 
rs.close(); 
stmt.close(); 
conn.close();

[amazon_carousel widget_type="SearchAndAdd" width="600" height="200" title="Books" market_place="" shuffle_products="False" show_border="False" keywords="MySQL" browse_node="" search_index="Books" /]

5 thoughts on “Connect to a MySql datasource in java

  1. Willian

    Connection conn = dataSource.getConnection();
    The DataSource class does not have this method.

    Reply
      1. Willian

        My inattention. The eclipse of imported javax.activation.DataSource (I trusted).
        Grateful for the return.

        Reply
        1. gerrit Post author

          Nice to see that it is working for you now. I will add the complete code as download soon (including the imports), so in the future it will be more easy for people to reproduce the steps in from my post.

          Reply
          1. Willian

            Some setbacks have arisen in the implementation. I found it interesting the solution adopted. I’m reading about and following the post.

Leave a Reply