Easy learning with example program codes

Steps to connect database in java

Steps to connect database in java using JDBC are given below:

  1. Load the JDBC driver.
  2. Connection.
  3. Statement.
  4. Execute statement.
  5. Close database connection.


1. Load the JDBC driver:

First step is to load or register the JDBC driver for the database. Class class provides forName() method to dynamically load the driver class.

Syntax: Class.forName(“driverClassName”);

To load or register OracleDriver class:


2. Create connection:

Second step is to open a database connection. DriverManager class provides the facility to create a connection between a database and the appropriate driver.To open a database connection we can call getConnection() method of DriverManager class.

Syntax: Connection connection = DriverManager.getConnection(url, user, password)

To create a connection with Oracle database:

Connection connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”user”,”password”);  

3. Create statement:

The statement object is used to execute the query against the database. Connection interface is act as a factory for statement object. A statement object can be any one of the Statement, CallableStatement, and PreparedStatement types .To create a statement object we have to call createStatement() method of Connection interface. Connection interface also provides the transaction management methods like commit() and rollback() etc.

Syntax: Statement stmt=conn.createStatement();

4. Execute statement:

Statement interface provides the methods to execute a statement.

To execute a statement for select query use below:

ResultSet resultSet = stmt.executeQuery(selectQuery);  

5. Close database connection:

After done with the database connection we have to close it. Use close() method of Connection interface to close database connection. The statement and ResultSet objects will be closed automatically when we close the connection object.

Syntax: connection.close();
Next Topic: Connect to Oracle database with JDBC driver.
Previous Topic: JDBC driver.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.


Sign Up/ Sign In
Ask a Question

Copyright © 2018 CodesJava Protection Status SiteMap Reference: Java Wiki