Share on Google+Share on Google+

JDBC Connection Example

In this tutorial you will learn about java.sql.Connection interface, and how to use this interface to get a connection to the database

JDBC Connection Example

JDBC Connection is an interface of java.sql.*;  package. An connection object represents a connection with specific database. A single application can have more than one Connection object with a single database or more databases. It create a session with a database, this session have the Sql statement to execute and results are returned.

You can get a information about a connection Connection.getMetaData() method. This method returns a MetaData object, that contains the information about database and tables.

To create a connection with database you need to call a method DriverManager.getConnection("ConnectionURL");. This returns a reference of a connection to the connection object.


The above code registers the river for MySql database.

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","userName","userPassword");

Now lets see an example to establish the connection to the MuSql database.

At first create a database named 'student' in MySql and then create a table named 'student'.

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

JDBCCOnnectionExample .java


import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCCOnnectionExample {
	Connection connection = null;

	public JDBCCOnnectionExample() {
		try {
		} catch (ClassNotFoundException e) {

	public Connection createConnection() {
		Connection con = null;
		if (connection != null) {
			System.out.println("Cant create a connection");
		} else {
			try {
				con = DriverManager.getConnection(
						"jdbc:mysql://localhost:3306/student", "root",
				System.out.println("Connection created Successfully");
				DatabaseMetaData dbMetaData = con.getMetaData();
				ResultSet dbInfo = dbMetaData.getCatalogs();
				System.out.println("Getting Concurrency of MetaData");
			} catch (SQLException e) {
		return con;

	public static void main(String[] args) throws SQLException {
		JDBCCOnnectionExample jdbccOnnectionExample = new JDBCCOnnectionExample();
		Connection conn = jdbccOnnectionExample.createConnection();

When you run this application it will display message as shown below:

Connection created Successfully
Getting Concurrency of MetaData

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.