How do you connect database in java programs?

(Last Updated On: December 3, 2017)

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