Jul 15 2012

Connect to a MySql datasource in java

Posted by Gerrit Schimpf in Java, MySQL

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 Responses to “Connect to a MySql datasource in java”

  1. Willian Says:

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

  2. Gerrit Says:

    Check out the api for the DataSource class. It does have the getConnection() method. Are you using the correct jar: mysql connector/J? Here some links which can help find the solution of your problem:

    http://docs.oracle.com/javase/1.4.2/docs/api/javax/sql/DataSource.html
    http://dev.mysql.com/doc/refman/5.1/en/connector-j.html

  3. Willian Says:

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

  4. gerrit Says:

    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.

  5. Willian Says:

    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

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


× 1 = seven