How do you connect database in java programs?

JDBC driver is used to connect database in java programs. We need to install compatible jdbc drivers for different types of databases i.e. MySQL, Oracle and SQL Server etc.

JDBC driver contains classes and interfaces to establish connection between java application and databases.

Lets consider an example with simple steps to connect oracle database from java program using JDBC connection and execute sql query. (eclipse and oracle jdbc)

  • First we need to load and register driver class using Class.forName(“oracle.jdbc.OracleDriver”).
  • Then we need to call getConnection method of DriverManager class with host name, user and password .
  • After that create statement using createStatement() method on connection object. Connection object is returned by device manager in above step.
  • Now we can construct sql query string what ever query we want to perform and  pass it to executeQuery(sql) method on statement object. It will return a result set. Then process the result set whatever you want to and then close the result set and connection.

Example to connect oracle database in java program

import java.sql.*;
public class JdbcConnection {

	public static void main(String[] args) {
		try {
			
			/*-----------------------------------
			 * load and register jdbc driver in java program			
			 */
			
			Class.forName("oracle.jdbc.OracleDriver");
			
			/*-----------------------------------
			 * Establish connection to connect database in java program
			 */
			
			Connection com=DriverManager.getConnection(
					"jdbc:oracle:thin:@localhost:1521:xe", 
					"system","password");
	         
			/*-----------------------------------
			 * Create statement object and construct 
			 * SQL Query to execute.			 
			 */
			
			Statement st=com.createStatement();
			String sql="select * from student ";
	         
			/*-----------------------------------
			 * execute sql query that return result set
			 * from database
			 */
	         ResultSet result=st.executeQuery(sql);
	         
	                  /*-----------------------------------
		           *Display result from result set				
			 */
	         
	         while(result.next()) {
	        	 System.out.println(
	        			 "ID="+result.getInt("ID")+" "
	        			 		+ "Name= "+result.getString("Name"));
	        
	         }
	         result.close();
	         
		} catch (SQLException e) {
			
			System.out.println(e);
			
		} catch (ClassNotFoundException e) {
			
			System.out.println(e);
		}
		
	}
}

Related Posts