Home > DeveloperSection > Interviews > What are the steps to connect to the database in java?

Posted on    May-15-2015 11:36 PM

 Java Java 
Ratings:
 1 Answer(s)
  354  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Points:4035
Posted on    May-15-2015 11:36 PM

1.Registering the driver class
2.Creating connection
3.Creating statement
4.Executing queries
5.Closing connection

Example:
import java.sql.*;  
class OracleCon{  
public static void main(String args[]){  
try{  
//step1 load the driver class  
Class.forName("oracle.jdbc.driver.OracleDriver");  
  
//step2 create  the connection object  
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  
//step3 create the statement object  
Statement stmt=con.createStatement();  
  
//step4 execute query  
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
  
//step5 close the connection object  
con.close();  
  
}catch(Exception e){ System.out.println(e);}  
  
}  
}  



Don't want to miss updates? Please click the below button!

Follow MindStick