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 .
ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
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();