5 steps to connect any java application with the database in java using JDBC.
- Register the driver class
- Creating connection
- Creating statement
- Executing queries
- Close connection
1) Register the driver class:The forName() method of Class is used to register the driver class. It used to dynamically load the driver class.
Example:
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.
It can be use with different parameter :
- 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:1521:xe","system","password");
3) Create the Statement object: The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.
Example:
Statement stmt=con.createStatement();
4) Execute the query: The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.
Example:
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object: The close() method of Connection interface is used to close the connection with database.
Example
con.close();