Friday, 25 December 2015

Steps to connect to the database in Java

There are 5 steps to connect any java application with the database in java using JDBC. They are as follows:
  • Register the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection

2.1 Register the driver class:

Class.forName() is used to load the driver class explicitly.

Example to register the OracleDriver class:

Class.forName("oracle.jdbc.driver.OracleDriver");  

Example to register with JDBC-ODBC Driver:


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 

2.2 Create the connection object:

getConnection() method of DriverManager class is used to create a connection. 

Syntax:
getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)
Example establish connection with Oracle Driver:


Connection con = DriverManager.getConnection
                    ("jdbc:oracle:thin:@localhost:1521:XE","username","password");

 Example establish connection with JDBC-ODBC Driver:

 Connection con = DriverManager.getConnection("jdbc:odbc:TOY2","root","root");

 2.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. 

Syntax:


public Statement createStatement() throws SQLException

Example to create a SQL statement:
Statement s=con.createStatement();
 

2.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.

Syntax :

public ResultSet executeQuery(String sql)throws SQLException  
 
Example to execute query:

ResultSet rs=stmt.executeQuery("select * from emp");     
while(rs.next())
{   
System.out.println(rs.getInt(1)+" "+rs.getString(2));   
}  

2.5 Close the connection object:


By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.

Syntax:

public void close()throws SQLException  
 
Example to close connection:

con.close(); 

No comments:

Post a Comment

HOW TO STOP WINDOWS 10 AUTO UPDATE