You are on page 1of 23

JAVA JDBC

Java JDBC

 Java JDBC is a Java API to connect and execute query with the database. JDBC
API uses jdbc drivers to connect with the database.
 We can use JDBC API to handle database using Java program and can perform
following activities:
 Connect to the database
 Execute queries and update statements to the database
 Retrieve the result received from the database.
JDBC Driver

 JDBC Driver is a software component that enables java application to interact


with the database. There are 4 types of JDBC drivers:
 JDBC-ODBC bridge driver
 Native-API driver (partially java driver)
 Network Protocol driver (fully java driver)
 Thin driver (fully java driver)
JDBC-ODBC bridge driver

 The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
This is now discouraged because of thin driver.
 Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that
you use JDBC drivers provided by the vendor of your database instead of the JDBC-
ODBC Bridge.
 Advantages:
 easy to use.
 can be easily connected to any database.
 Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC function calls.
 The ODBC driver needs to be installed on the client machine.
Native-API driver
 The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into native
calls of the database API. It is not written entirely in java.
 Advantage:
 performance upgraded than JDBC-ODBC bridge driver.
 Disadvantage:
 The Native driver needs to be installed on the each client
machine.
 The Vendor client library needs to be installed on client
machine.
Network Protocol driver
 The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is fully written in java.
 Advantage:
 No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging
etc.
 Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier.
Thin driver

 The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in J
 Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.
 Disadvantage:
 Drivers depend on the Database.
 ava language.
Database Connectivity with MS-ACCESS
import java.sql.*;
class Conn
{ public static void main(String [] args)
{ try{  //step1 load the driver class  
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//step2 create  the connection object  
Connection con=DriverManager.getConnection("jdbc:odbc:dsn");
//step3 create the statement object  
Statement st=con.createStatement();
//step4 execute query  
ResultSet rs=st.executeQuery("select * from employee");
while(rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
} //step5 close the connection object
con.close();
}catch(Exception e){System.out.println(e);}
}}
 Open Ms-Access and create one table
 Save the file and close.
 To create dsn in the odbc (dsn-data source name)
 For 64 bit System
 C:\  windows  syswow64  odbcad32.exe  double click  odbc windows  add
 Access driver (*mdb , *accdb )
 Accessndriver(*mdb)
 Finish  DataSourceName  (dsn)  select select database  ok  ok ok
 For 32 bit system
 Control panel  adm tool  DataSource (odbc)  add

Note: Do not open the file during connection


Note:- to run this file  set path= jdk 1.7
Example to Connect Java Application with Oracle database
1.import java.sql.*;  
2.class OracleCon{  
3.public static void main(String args[]){  
4.try{  //step1 load the driver class  
5.Class.forName("oracle.jdbc.driver.OracleDriver");  
6.//step2 create  the connection object  
7.Connection con=DriverManager.getConnection(  
8."jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
9.//step3 create the statement object  
10.Statement stmt=con.createStatement();  
11.//step4 execute query  
12.ResultSet rs=stmt.executeQuery("select * from emp");  
13.while(rs.next())  
14.System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
15.//step5 close the connection object  
16.con.close();  
17.}catch(Exception e){ System.out.println(e);}  
18.}  }  
 To connect java application with the Oracle database ojdbc14.jar file is required to
be loaded.
 Two ways to load the jar file:
 paste the ojdbc14.jar file in jre/lib/ext folder
 set classpath
 paste the ojdbc14.jar file in JRE/lib/ext folder:
 set classpath:
 Temporary
 C:>set classpath=c:\folder\ojdbc14.jar;.;  
 Permanent
 Go to environment variable then click on new tab. In variable name write classpath and in variable
value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
Java Database Connectivity with MySQL

1.import java.sql.*;  
2.class MysqlCon{  
3.public static void main(String args[]){  
4.try{  
5.Class.forName("com.mysql.jdbc.Driver");  
6.Connection con=DriverManager.getConnection(  
7."jdbc:mysql://localhost:3306/sonoo","root","root");  
8.//here sonoo is database name, root is username and password  
9.Statement stmt=con.createStatement();  
10.ResultSet rs=stmt.executeQuery("select * from emp");  
11.while(rs.next())  
12.System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
13.con.close();  
14.}catch(Exception e){ System.out.println(e);}  
15.}  
16.}  
 To connect java application with the mysql database, mysqlconnector.jar file is
required to be loaded.
 Two ways to load the jar file:
 Paste the mysqlconnector.jar file in jre/lib/ext folder
 Set classpath
 Temporary
 C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.; 
 Permanent
 Go to environment variable then click on new tab. In variable name
write classpath and in variable value paste the path to the mysqlconnector.jar file by
appending mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;
Connectivity with Access without DSN
Connectivity with type1 driver is not considered good. To connect java application with type1 driver, create DSN first,
here we are assuming your dsn name is mydsn.
1.import java.sql.*;  
2.class Test{  
3.public static void main(String ar[]){  
4. try{  
5.   String url="jdbc:odbc:mydsn";  
6.   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
7.   Connection c=DriverManager.getConnection(url);  
8.   Statement st=c.createStatement();  
9.   ResultSet rs=st.executeQuery("select * from login");  
10.    
11.   while(rs.next()){  
12.    System.out.println(rs.getString(1));  
13.   }  
14.  
15.}catch(Exception ee){System.out.println(ee);}  
16.  
17.}}  
1.import java.sql.*;  
2.class FetchRecord{  
3.public static void main(String args[])throws Exception{  
4.Class.forName("oracle.jdbc.driver.OracleDriver");  
5.Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:xe","system","oracle");  
6.Statement stmt=con.createStatement();  
7.  
8.//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");  
9.//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=1000
0 where id=33");  
10.int result=stmt.executeUpdate("delete from emp765 where id=33");  
11.System.out.println(result+" records affected");  
12.con.close();  
13.}}  
1.import java.sql.*;  
2.class FetchRecord{  
3.public static void main(String args[])throws Exception{  
4.  
5.Class.forName("oracle.jdbc.driver.OracleDriver");  
6.Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","
oracle");  
7.Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_
UPDATABLE);  
8.ResultSet rs=stmt.executeQuery("select * from emp765");  
9.  
10.//getting the record of 3rd row  
11.rs.absolute(3);  
12.System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));  
13.  
14.con.close();  
15.}}  
import java.sql.*;
class create
{ public static void main(String s[])
{ try{ Connection con=ConnectionProvider.get();
Statement st=con.createStatement();
// int x=st.executeUpdate("insert into student values(104,'hhh',88,'A')");
// int x=st.executeUpdate("delete from student where strollno=102");
// int x=st.executeUpdate("update student set stname='trp' where strollno=102");
int x=st.executeUpdate("create table emp1(emp_no number(4),emp_name varchar2(20), emp_salary number(5))");
System.out.println("value of x is "+x);
x=st.executeUpdate("insert into emp1 values(1111,'Ashish',18000)");
System.out.println("value of x is "+x);
/*if(x==1)
System.out.println("Table create successfully ");
else
System.out.println("Sorry ..... Could not create");*/
ResultSet rs=st.executeQuery("select * from emp1");
while(rs.next())
{ System.out.print(rs.getString(1));
System.out.print("\t"+rs.getString(2));
System.out.println("\t"+rs.getInt(3)); }
} catch(SQLException e)
{ e.printStackTrace(); }
}}
import java.sql.*;
class update
{ public static void main(String s[])
{ try{
Connection con=ConnectionProvider.get();
Statement st=con.createStatement();
// int x=st.executeUpdate("insert into student values(104,'hhh',88,'A')");
// int x=st.executeUpdate("delete from student where strollno=102");
int x=st.executeUpdate("update student set stname='trp' where strollno=102");
if(x==1)
System.out.println("Record updated successfully ");
else
System.out.println("Sorry ..... Could not update");
ResultSet rs=st.executeQuery("select * from student");
while(rs.next())
{
System.out.print(rs.getString(1));
System.out.print("\t"+rs.getString(2));
System.out.print("\t"+rs.getInt(3));
System.out.println("\t"+rs.getString(4));
}
} catch(SQLException e)
{ e.printStackTrace(); }
}}
import java.sql.*;
import java.io.*;
class TransactionTest
{
public static void main(String s[])
{
Connection con=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","kavita","kvt123");
System.out.println("Connection prepare");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PreparedStatement ps=con.prepareStatement("insert into student values(?,?,?,?)");
con.setAutoCommit(false);
for(int i=1; i<=5; i++)
{
System.out.println("Enter the rollno, name ,marks and grade for "+i+" student ");
int rno=Integer.parseInt(br.readLine());
String name=br.readLine();
int marks=Integer.parseInt(br.readLine());
String grade=br.readLine();
ps.setInt(1,rno);
ps.setString(2,name);
ps.setInt(3,marks);
ps.setString(4,grade);
ps.executeUpdate();
}
con.commit();
System.out.println("All records committed successfully");
}
catch(SQLException e)
{ System.out.println(e);
try{
con.rollback();
System.out.println("Queries are rollbacked");
}
catch(Exception ee)
{
ee.printStackTrace();
}
}
catch(Exception e)
{
System.out.println(e);
} }}
import java.io.*;
import java.sql.*;
public class StoreFile
{ public static void main(String []args)
{ try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","kavita","kvt123");
System.out.println("Connection prepare");
PreparedStatement ps=con.prepareStatement("insert into student2 values(?,?)");
//preparing the stream
File f=new File("e:\\resume.txt");
FileReader fr=new FileReader(f);

ps.setInt(1,101);
ps.setCharacterStream(2,fr,(int)f.length());
int i=ps.executeUpdate();
System.out.println(i+" record inserted");
con.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
import java.sql.*;

class ConnectionProvider
{
private static Connection con;
static
{
try{
//Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Class Loaded");
//con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","kavita","kvt123");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/kavita","root","mysql");
System.out.println("Connection Prepared");
}
catch(Exception e)
{
e.printStackTrace();
}
} static Connection get()
{ return(con);}
}
import java.sql.*;
class delete
{ public static void main(String s[])
{ try{
Connection con=ConnectionProvider.get();
Statement st=con.createStatement();
// int x=st.executeUpdate("insert into student values(104,'hhh',88,'A')");
int x=st.executeUpdate("delete from student where strollno=101");
if(x==1)
System.out.println("Record delete successfully ");
else
System.out.println("Sorry ..... Could not delete");
ResultSet rs=st.executeQuery("select * from student");
while(rs.next())
{
System.out.print(rs.getString(1));
System.out.print("\t"+rs.getString(2));
System.out.print("\t"+rs.getInt(3));
System.out.println("\t"+rs.getString(4));
}
} catch(SQLException e)
{ e.printStackTrace(); }
}}

You might also like