13JDBC

Embed Size (px)

Citation preview

  • 8/2/2019 13JDBC

    1/25

  • 8/2/2019 13JDBC

    2/25

    Java Database Connectivity

    JDBC(Java Database Connectivity) is defined, as a set of javaclasses and methods to interface with database.

    It also provides uniform access to a wide range of relationaldatabase. The java software bundle includes JDBC-ODBCbridge.

  • 8/2/2019 13JDBC

    3/25

    Database Connectivity

    For any application to communicate with the database, itneeds have the following in formations:

    1) The RDBMS/DBMS product is used to which the databasecreated

    2) Where database reside(Location).

    3) The name of the database.So, we use JDBC calls to retrieve and update informationfrom a database using JDBC. This involves the followingfunctions:-a) Opening and establish a database connectionb) Send SQL statementsc) Process the returned result set.d) Close the database connection

  • 8/2/2019 13JDBC

    4/25

    JDBC APIJava Database Connectivity provides a database programming

    API for java programs.

    Java programs cannot directly communicate with the ODBCdriver. Sun Microsystems provides a JDBC-ODBC bridgethat translate JDBC to ODBC. There are several type ofJDBC 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)

  • 8/2/2019 13JDBC

    5/25

    There are 4 types of drivers available in java for databaseconnectivity. Type 3 and 4 are pure drivers where as type 1and 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.

  • 8/2/2019 13JDBC

    6/25

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

    If the middleware is to run of different platforms then type 4driver might be more effective.

  • 8/2/2019 13JDBC

    7/25

    JDBC DriversThe connection to the database is handled by the JDBC

    Driver class.

    The Java SDK contains only one JDBC driver, a jdbc-odbc bridge that can communicate with an existing OpenDataBase Conectivity (ODBC) driver. Other databases needa 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");

  • 8/2/2019 13JDBC

    8/25

    Each JDBC driver is configured to understand a specific URLso multiple JDBC drivers can be loaded at any one time.

    When you specify a URL at connect time, the first matchingJDBC driver is selected.

    The jdbc-odbc bridge accepts Uniform Resource Locators(URLs) starting with jdbc:odbc: and uses the next field inthat URL to specify the data source name. The data sourcename identifies the particular database scheme you wish toaccess. The URL can also include more details on how tocontact the database and enter the account.

  • 8/2/2019 13JDBC

    9/25

    JDBC Application Architecture

    Java Application orApplet

    JDBC API

    JDBC Driver Manager

    JDBC-ODBC BridgeDriver

    ODBC

    Database Library

    Database/ DatabaseServer

    Client Machine

    Server Machine (Business Logic)

    Access DriverMySQL Driver

  • 8/2/2019 13JDBC

    10/25

    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 toquery. A ResultSet is returned to an application when a SQLquery is executing a statement object.

  • 8/2/2019 13JDBC

    11/25

    Types of statements1) Statement:- Top most interface which provides basic

    methods useful for executing SELECT, INSERT, UPDATEand 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 withdifferent parameter values specified for each execution.

    3) CallableStatement:- It allows you to execute storeprocedures within a RDBMS which supports storedprocedures.The callable statement has methods for retrieving thereturn values of the stored procedure.

  • 8/2/2019 13JDBC

    12/25

  • 8/2/2019 13JDBC

    13/25

    We can able to create the ResultSet scrollable andupdateable.

    Stmt=con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONUR_READ_ONLY);

    Stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONUR_UPDATABLE);

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

    ResultSetForward only

    Read only

  • 8/2/2019 13JDBC

    14/25

    rs.first()

    rs.insertRow();rs.updateInt(1, 101);

    rs.updateString(2,sss);

    rs.moveToInsertRow();

    rs.moveToCurrentRow();

    rs.first()

    rs.deleteRow();

    ipaddress

  • 8/2/2019 13JDBC

    15/25

    package myClasses;

    import java.sql.*;

    class MyConnection {

    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="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);

    }

    }}

    }

    Check exception

    Interface

    Class inlang

    packageProvide connection from database

    Id of service namePort no

    ipaddressURL protocol

    package

  • 8/2/2019 13JDBC

    16/25

    JDBC without try-catch

    package myClasses;

  • 8/2/2019 13JDBC

    17/25

    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");

    }

    }

  • 8/2/2019 13JDBC

    18/25

    Oracle connectivity

    package myClasses;

  • 8/2/2019 13JDBC

    19/25

    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;

  • 8/2/2019 13JDBC

    20/25

    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);

    }

    }

    }

    }

  • 8/2/2019 13JDBC

    21/25

    MySQL

    package myClasses;

  • 8/2/2019 13JDBC

    22/25

    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;

  • 8/2/2019 13JDBC

    23/25

    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;

  • 8/2/2019 13JDBC

    24/25

    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;

    i j l *

  • 8/2/2019 13JDBC

    25/25

    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