Google News
logo
What are the steps to connect to the JDBC database in java?


* Registering the driver class :
The forName() method of the Class class is used to register the driver class. This method is used to load the driver class dynamically. Consider the following example to register OracleDriver class.
 
Class.forName("oracle.jdbc.driver.OracleDriver"); 

* Creating connection :
The getConnection() method of DriverManager class is used to establish the connection with the database. The syntax of the getConnection() method is given below.
public static Connection getConnection(String url)throws SQLException  
public static Connection getConnection(String url,String name,String password)  
throws SQLException ​
 
Consider the following example to establish the connection with the Oracle database.
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","password");

 

* Creating the statement :
The createStatement() method of Connection interface is used to create the Statement. The object of the Statement is responsible for executing queries with the database.
 
public Statement createStatement()throws SQLException  

consider the following example to create the statement object
 
Statement stmt=con.createStatement();

* Executing the queries :
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.
 
Syntax of executeQuery() method is given below :
 
public ResultSet executeQuery(String sql)throws SQLException
  
Example to execute the query
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next()){  
System.out.println(rs.getInt(1)+" "+rs.getString(2));  
} ​
 
However, to perform the insert and update operations in the database, executeUpdate() method is used which returns the boolean value to indicate the successful completion of the operation.

* Closing connection :
By closing connection, object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.
 
Syntax of close() method is given below :
 
public void close()throws SQLException
  
Consider the following example to close the connection.
 
con.close();

LATEST ARTICLES