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.
public static void forName(String className)throws ClassNotFoundException
Example to register the Oracle driver class:
2) Create the Connection Object:
The getConnection() method of DriverManager class is used to establish connection with the database.
There are 2 ways.
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
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.
public Statement createStatement()throws SQLException
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.
public ResultSet executeQuery(String sql)throws SQLException
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");
5) Close Database connection:
By closing connection, statement and resultSet objects will be closed automatically. We use the method close() of connection interface.
public void close()throws SQLException