JDBC DataSource Example


 

JDBC DataSource Example

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

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 (
RollNo int(9)  PRIMARY KEY NOT NULL,
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') ;

DataSourceExample.java

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() {
		bdSource.setDriverClassName("com.mysql.jdbc.Driver");
		bdSource.setUrl("jdbc:mysql://localhost:3306/student");
		bdSource.setUsername("root");
		bdSource.setPassword("root");
	}

	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 (rs.next()) {
			System.out.println("Name- " + rs.getString("Name") + ", Roll No- "
					+ rs.getInt("RollNo") + ", Course- "
					+ rs.getString("Course") + ", Address- "
					+ rs.getString("Address"));
		}
		con.close();
		stmt.close();
		rs.close();
	}
}
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

Ads