Share on Google+Share on Google+

JDBC DataSource Example

In this tutorial you will learn about JDBC DataSource, and how to use DataSource to get a connection

JDBC DataSource Example

You can establish a connection to a database either using DriverManager class or DataSource interface. JDBC DataSource is an interface of package javax.sql.DataSource. This interface is mostly preferred over DriverManager class because it allows the detail about database to your application program. DataSource object increases the application portability .

An example given below is an example of BasicDataSourse example. To run this example you must create a databse in MySql database named student and create table of name student as,

CREATE TABLE student (
Name tinytext NOT NULL,
Course varchar(25) NOT NULL,
Address text

Insert Value Into student table

INSERT INTO student VALUES(1, 'Vinay', 'MCA',Delhi') ;

INSERT INTO student VALUES(2, 'Ram', 'BCA', Patna') ;

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

import org.apache.commons.dbcp.BasicDataSource;

public class DataSourceExample {
	Connection connection = null;
	BasicDataSource bdSource = new BasicDataSource();

	public DataSourceExample() {

	public Connection createConnection() {
		Connection con = null;
		try {
			if (connection != null) {
				System.out.println("Cant create a New Connection");
			} else {
				con = bdSource.getConnection();
				System.out.println("Connection Done successfully");
		} catch (Exception e) {
			System.out.println("Error Occured " + e.toString());
		return con;

	public static void main(String args[]) throws Exception {
		DataSourceExample dsExample = new DataSourceExample();
		Connection con = dsExample.createConnection();
		Statement stmt = con.createStatement();
		String query = "SELECT * FROM student";
		ResultSet rs = stmt.executeQuery(query);
		while ( {
			System.out.println("Name- " + rs.getString("Name") + ", Roll No- "
					+ rs.getInt("RollNo") + ", Course- "
					+ rs.getString("Course") + ", Address- "
					+ rs.getString("Address"));
When you run this application it will display message as shown below:

Connection Done successfully
Name- Vinay, Roll No- 1, Course- MCA, Address- Motihari
Name- Ram, Roll No- 2, Course- BCA, Address- Patna

Download this example code


Posted on: October 16, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.