Steps for JDBC program:

1.Register driver:
Register a particular driver to the application by using java.lang.Class class’s forName() method.
Class.forName(“oracle.jdbc.driver.OracleDriver”)
Or
Driver md=new oracle.jdbc.driver.OracleDriver();
java.sql.DriverManager.registerDriver(md);

2.Creating Connection:
A connection created by using getConnection() method of DriverManager class. The method needs data source name to be used as sub name in the database naming.
Connection con= java.sql.DriverManager.getConnection(url) ;
Connection con= java.sql.DriverManager.getConnection(url,uid,pwd) ;

3.Building Statement
To send SQL statements to SQL engine it is necessary create statement by using createStatement() method of Connection class.
Statement stmt= con.createStatement();

4. Getting Result set
A result set can be otained by executing executeQuery() of Statement class as
ResultSet rs=stmt.executeQuery(“sql statement”);

5.DML and DDL
The executeUpdate() of created statement to update and insert in database and returns no of rows affected.

6.Close statement,connection by using close() method of respective class.
Example:
Here we have used type-4 driver. So do not forget to give that ojdbc14.jar in classpath.
This program insert the values in emp table.
import java.sql.*;
class demo
{
public static void main(String[] args){
Connection con=null;
Statement stmt=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
stmt=con.createStatement();
boolean b=stmt.execute("insert into emp values(3,'bbc','chennai')");
if(b)System.out.println("insert successful");
else System.out.println("insert not success");
}catch(Exception e){
System.out.println("the exception is::::->"+e);
}
finally{
try{
stmt.close();
con.close();}
catch(Exception e){
System.out.println("2nd try block exception:::->"+e);}}}};

No comments:

Post a Comment