JDBC - How to get Connection from DataSource example

Posted on January 28, 2017


Technologies used:   JDK 1.8.0_121 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

In our previous post, we have used DriverManager class to get connection object from a data source.

In this section, we will show you how to create and use a DataSource object to get a connection to your data source without using JNDI services.

JAR dependencies

Download the MySQL JDBC driver from https://dev.mysql.com/downloads/connector/j/ and add to build path of your project.

JDBC DataSource + MySQL example

The following example demonstrates how to get connection from MySQL DataSource.

DataSourceExample.java

package com.boraji.tutorial.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mysql.cj.jdbc.MysqlDataSource;

/**
 * @author imssbora
 */
public class DataSourceExample {
  
  public static DataSource getMysqlDataSource() {
    MysqlDataSource dataSource = new MysqlDataSource();

    // Set dataSource Properties
    dataSource.setServerName("localhost");
    dataSource.setPortNumber(3306);
    dataSource.setDatabaseName("BORAJI");
    dataSource.setUser("root");
    dataSource.setPassword("admin");
    return dataSource;
  }

  public static void main(String[] args) {

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {

      // Get connection from DataSource
      conn = getMysqlDataSource().getConnection();
      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT version()");
      
      if (rs.next()) {
        System.out.println("Database Version : " + rs.getString(1));
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (rs != null) {
          rs.close();
        }
        if (stmt != null) {
          stmt.close();
        }
        if (conn != null) {
          conn.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}

Output

Database Version : 5.7.12-log