Database connection in Java

In the previous post, we have learnt about Collection Framework. In this post, we will see how to connect to the database in java.

There are following steps which we need to follow to connect to a database.

  • Register the Driver Class
  • Create the connection
  • Create the statement Object
  • Execute the queries
  • Close Database connection

Let’s understand all these steps one by one.

1) Register the Driver Class:

The forName() method of Class ‘class’ is used to register the driver class. It loads the driver class dynamically.

Syntax:

public static void forName(String className)throws ClassNotFoundException

Example to register the Oracle driver class:

Class.forName(“oracle.jdbc.driver.OracleDriver”); 

2) Create the Connection Object:

The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax:

There are 2 ways.

public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
throws SQLException

Example:

Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@<localhost>:<port no>:<DB name>”,”user”,”password”);

3) Create the statement Object:

The createStatement() method of Connection interface is used to create statement. The object of statement is used to execute queries with the database connection.

Syntax:

public Statement createStatement()throws SQLException

Example:

Statement stmt=con.createStatement();

4) Execute the query:

The method executeQuery() od statement interface is used to execute the query with the database.This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax:

public ResultSet executeQuery(String sql)throws SQLException

Example:

After getting the resultset object, we can create a while loop where we can fetch the record with the method next(). Column values can be fetched by using methods getInt , getString depending on the data type .

5) Close Database connection:

By closing connection, statement and resultSet objects will be closed automatically. We use the method close() of connection interface.

Syntax:

public void close()throws SQLException

Example:

con.close();


Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Print Friendly, PDF & Email
Find out words occurrences in a file
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

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