Sunteți pe pagina 1din 25

Java Database Connectivity

JDBC(Java Database Connectivity) is defined, as a set of java classes and methods to interface with database.
It also provides uniform access to a wide range of relational database. The java software bundle includes JDBC-ODBC bridge.

Database Connectivity For any application to communicate with the database, it needs have the following in formations:
1) The RDBMS/DBMS product is used to which the database

created 2) Where database reside(Location). 3) The name of the database. So, we use JDBC calls to retrieve and update information from a database using JDBC. This involves the following functions:a) Opening and establish a database connection b) Send SQL statements c) Process the returned result set. d) Close the database connection

JDBC API
Java Database Connectivity provides a database programming API for java programs. Java programs cannot directly communicate with the ODBC driver. Sun Microsystems provides a JDBC-ODBC bridge that translate JDBC to ODBC. There are several type of JDBC drivers available. They are:1) JDBC-ODBC bridge + ODBC driver (Type 1 Driver)

2) Native API partly java Driver (Type 2 Driver)


3) JDBC-Net Pure java Driver (Type 3 Driver) 4) Native protocol Pure java Driver (Type 4 Driver)

There are 4 types of drivers available in java for database connectivity. Type 3 and 4 are pure drivers where as type 1 and 2 are impure drivers.

Type 1: Disadvantages: It is not suitable for large-scale application. They are the slowest of all. ODBC drivers installed on each client machine typically the case for windows-based machines.

Type 2: Disadvantage: For this, user needs to make sure the JDBC driver of the database vendor is loaded onto each client machine.

Type 3: Disadvantages: It needs some database-specific code on the middleware server. If the middleware is to run of different platforms then type 4 driver might be more effective.

JDBC Drivers
The connection to the database is handled by the JDBC Driver class. The Java SDK contains only one JDBC driver, a jdbcodbc bridge that can communicate with an existing Open DataBase Conectivity (ODBC) driver. Other databases need a JDBC driver specific to that database. These next lines of code show how to load three different JDBC driver classes: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("postgresql.Driver"); Class.forName("oracle.jdbc.driver.OracleDriver");

Each JDBC driver is configured to understand a specific URL so multiple JDBC drivers can be loaded at any one time. When you specify a URL at connect time, the first matching JDBC driver is selected.
The jdbc-odbc bridge accepts Uniform Resource Locators (URLs) starting with jdbc:odbc: and uses the next field in that URL to specify the data source name. The data source name identifies the particular database scheme you wish to access. The URL can also include more details on how to contact the database and enter the account.

JDBC Application Architecture


Java Application or Applet
Client Machine JDBC API

JDBC Driver Manager Server Machine (Business Logic) JDBC-ODBC Bridge Driver Access Driver MySQL Driver Database/ Database Server Database Library

ODBC

Main Objects of the JDBC API include DataSource/DriverManager :- used to establish a connection
Connection :- controls the connection to the database Statement :- object are used for executing SQL statements: SELECT, INSERT, UPDATE, DELETE. ResultSet :- Object act like a workspace to store the results to query. A ResultSet is returned to an application when a SQL query is executing a statement object.

Types of statements
1) Statement:- Top most interface which provides basic methods useful for executing SELECT, INSERT, UPDATE and DELETE sql statements.
2) PreparedStatement:- It is used when an application

plans to specify parameters to your sql queries. This statement can be executed multiple times with different parameter values specified for each execution.
3) CallableStatement:- It allows you to execute store

procedures within a RDBMS which supports stored procedures. The callable statement has methods for retrieving the return values of the stored procedure.

Forward only

ResultSet
Read only

We can able to create the ResultSet scrollable and updateable.

Stmt=con.createStatement(ResultSet.TYPE_FORWARD_O

NLY, ResultSet.CONUR_READ_ONLY);
Stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENS

ITIVE, ResultSet.CONUR_UPDATABLE);
ResultSet rs= stmt.executeQuery(select * from student);

rs.first() rs.insertRow(); rs.updateInt(1, 101); rs.updateString(2,sss); rs.moveToInsertRow(); rs.moveToCurrentRow(); rs.first() rs.deleteRow();

ipaddress package myClasses; URL protocol import java.sql.*; class MyConnection { package public static void main(String args[]) { Connection con= null; Statement stmt=null; try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "admin"); Class in

Interface
Port no Id of service name Provide connection from database

lang package

stmt=con.createStatement(); String sql="Insert into student values (101, 'Ram')"; stmt.executeUpdate(sql); System.out.println("Data inserted successfully"); } catch(ClassNotFoundException c) { System.out.println(c); } catch(SQLException s) { System.out.println(s); } finally { try { if(stmt != null) { stmt.close(); } if(con !=null) { con.close(); }

Check exception

} catch(SQLException s) { System.out.println(s); } } } }

JDBC without try-catch

package myClasses;

import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement;


public class JDBCwithoutTRY { public static void main(String args[]) { Connection con= null; Statement stmt=null;

Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "admin");


stmt=con.createStatement(); String sql="Insert into student values (101, 'Ram')"; stmt.executeUpdate(sql); System.out.println("Data inserted successfully"); } }

Oracle connectivity

package myClasses; import java.sql.*; class MyConnection1 { 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:iit", "scott", "tiger"); stmt=con.createStatement(); String sql="Insert into student values (102, 'Mohan')"; stmt.executeUpdate(sql); System.out.println("Data inserted successfully"); } catch(ClassNotFoundException c) { System.out.println(c); } catch(SQLException s) { System.out.println(s); } finally { try { if(stmt != null) { stmt.close(); } if(con !=null) { con.close(); } } catch(SQLException s) { System.out.println(s); } } } }

package myClasses; import java.sql.*; class MyConnection2 { public static void main(String args[]) { Connection con= null; Statement stmt=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:mydns", "scott", "tiger"); stmt=con.createStatement(); String sql="Insert into student values (101, 'Ram')"; stmt.executeUpdate(sql); System.out.println("Data inserted successfully"); } catch(ClassNotFoundException c) { System.out.println(c); } catch(SQLException s) { System.out.println(s); } finally { try { if(stmt != null) { stmt.close(); } if(con !=null) { con.close(); } } catch(SQLException s) { System.out.println(s); } } } }

MySQL

package myClasses; import java.sql.*; class MyConnection3 { public static void main(String args[]) { Connection con= null; Statement stmt=null; try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "admin"); stmt=con.createStatement(); String sql= "select * from student";

ResultSet rs= stmt.executeQuery(sql); while(rs.next()) { int roll= rs.getInt("id"); String name= rs.getString("name"); System.out.println("Roll : "+roll); System.out.println("Name : "+name); }
} catch(ClassNotFoundException c) { System.out.println(c); } catch(SQLException s) { System.out.println(s); } finally { try { if(stmt != null) { stmt.close(); } if(con !=null) { con.close(); } } catch(SQLException s) { System.out.println(s); } } } }

package myClasses; import java.sql.*;


class MyConnection4 { public static void main(String args[]) { Connection con= null; PreparedStatement pstmt=null; try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "admin");

pstmt=con.prepareStatement("Insert into student values (?, ?)"); pstmt.setInt(1, 102); pstmt.setString(2, "Joe"); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt.setInt(1, 103); pstmt.setString(2, "Raj"); pstmt.executeUpdate();

} catch(ClassNotFoundException c) { System.out.println(c); } catch(SQLException s) { System.out.println(s); } finally { try { if(pstmt != null) { pstmt.close(); } if(con !=null) { con.close(); }

}
catch(SQLException s) { System.out.println(s); } } } }

package myClasses; import java.sql.*; class MyConnection5 { public static void main(String args[]) { Connection con= null; Statement stmt=null; try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "admin"); con.setAutoCommit(false); stmt=con.createStatement(); String sql1= "insert into student values (105, 'Rama')"; String sql2= "insert into student values (106, 'Sahil')"; String sql3= "insert into student values (107, 'John')"; stmt.addBatch(sql1); stmt.addBatch(sql2); stmt.addBatch(sql3);

stmt.executeBatch(); con.setAutoCommit(true); System.out.println("Data inserted successfully");


} catch(ClassNotFoundException c) { System.out.println(c); } catch(SQLException s) { System.out.println(s); } finally { try { if(stmt != null) { stmt.close(); } if(con !=null) { con.close(); } } catch(SQLException s) { System.out.println(s); } } } }

package myClasses; import java.sql.*; import java.util.*; class MyConnection6 { public static void main(String args[]) { Connection con= null; PreparedStatement pstmt=null; try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "admin");

pstmt=con.prepareStatement("Insert into student values (?, ?)"); Student s1= new Student("108", "Chandan"); Student s2= new Student("109", "Avinash"); Student s3= new Student("110", "Divey"); ArrayList a1= new ArrayList(); a1.add(s1); a1.add(s2); a1.add(s3); for(int i=0; i<a1.size(); i++) { Student s=(Student) a1.get(i); pstmt.setString(1, s.getId()); pstmt.setString(2, s.getName()); pstmt.addBatch(); } pstmt.executeBatch(); System.out.println("Data inserted successfully."); } catch(ClassNotFoundException c) { System.out.println(c); } catch(SQLException s) { System.out.println(s); } finally { try { if(pstmt != null) { pstmt.close(); } if(con !=null) { con.close(); } } catch(SQLException s) { System.out.println(s); } } } }