How to connect database via jdbc in java code – Using java.sql.connection class
database connection can be established.
 
First register the driver as below;

Class.forName("oracle.jdbc.driver.OracleDriver");

 
Then using DriverManager.getConnection method create the connection.

DriverManager.getConnection(dbConnection,userId,password);

Also connection close method is available by calling method close() on Connection Object.
 
Make sure the driver jar file ojdbc6.jar is available in the classpath.
 
Complete class ConnectToDatabase.java can be found below;

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

public class ConnectToDatabase {

	/**
	 * @param args
	 * @throws SQLException 
	 */
	public static void main(String[] args) throws SQLException {
		
		// Call connectDatabase which returns Connection instance
		Connection con = connectDatabase("userName", "password", "jdbc:oracle:thin:@dbhost:port:orcl");
	
		// Call closeConnection which closes the Connection instance
		closeConnection(con);
	}
		
	public static Connection connectDatabase(String userId, String password, String dbConnection){
		try {

			Class.forName("oracle.jdbc.driver.OracleDriver");

		} catch (ClassNotFoundException e) {
			System.err.println("Unable to find Oracle JDBC Driver?");
			e.printStackTrace();
			return null;
		}

		Connection connection = null;

		try {
			connection = DriverManager.getConnection(
					dbConnection, 
					userId,
					password);

		} catch (SQLException e) {
			System.out.println("Connection Failed!");
			e.printStackTrace();
			return null;
		}

		if (connection != null) {
			System.out.println("Got Connection");
			return connection;
		} else {
			System.out.println("Connection Failed!");
		}
		
		return null;
	}
	
	/**
	 * 
	 * @throws SQLException
	 */
	public static void closeConnection(Connection con) throws SQLException{
		if(con!=null){
			System.out.println("Closing Connection");
			con.close();
		}		
	}
}

 
For official Java Docs refer http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html
 
For further reading refer Java Programming Category posts.

Share this post

How to connect database via jdbc in java code
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *