16. jdbc&sql pack

Upload: maleem

Post on 03-Jun-2018

233 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 16. Jdbc&SQL Pack

    1/19

    1

    Accessing a Database Using the java.sqlpack

  • 8/11/2019 16. Jdbc&SQL Pack

    2/19

    2

    JDBC is a standard Java class library, to query

    and modify relational data Import java.sql.*in your Java code

    JDBC is modeled after ODBC

    Supports SQL92 syntax and types

    Allows for vendor-specific extensions

    Many Oracle extensions

    What Is JDBC?

  • 8/11/2019 16. Jdbc&SQL Pack

    3/19

    3

    Relationship Between JDBC Classes

    ResultSet

    ResultSetMetaData

    DatabaseMetaData

    Statement

    Connection

    DriverManager

    1

    6

    4

    2

    3 5

  • 8/11/2019 16. Jdbc&SQL Pack

    4/19

    4

    Registering a JDBC Driver

    JDBC drivers must register themselves with theDriverManager

    Drivers register themselves automatically when

    they are loaded

    try {

    Class c = Class.forName(

    "sun.jdbc.odbc.JdbcOdbcDriver");

    }

    catch (ClassNotFoundException e) {

    e.printStackTrace();

    }

  • 8/11/2019 16. Jdbc&SQL Pack

    5/19

  • 8/11/2019 16. Jdbc&SQL Pack

    6/19

    6

    Example: Connecting to Oracle

    The following code connects toan Oracle database

    Uses the ODBC JDBC Bridge

    driver

    Connection conn;

    try {

    conn = DriverManager.getConnection(

    "jdbc:odbc:dsn_name", theUser","thePassword");

    }

    catch (SQLException e) {}

  • 8/11/2019 16. Jdbc&SQL Pack

    7/19

    7

    Obtaining Database Metadata

    Connectioncan be used to get a

    DatabaseMetaDataobject

    This provides many methods to obtain metadata

    for the database

    Connection conn; try {

    DatabaseMetaData dm = conn.getMetaData();

    String s1 = dm.getURL();

    String s2 = dm.getSQLKeywords();boolean b1 = dm.supportsTransactions();

    boolean b2 = dm.supportsSelectForUpdate();

    }

    catch (SQLException e) {}

  • 8/11/2019 16. Jdbc&SQL Pack

    8/19

    8

    Three interfaces are defined, providing the

    following capabilities:

    Execute queries and other

    DML/DDL operationsExecute precompiled

    statements

    Call stored procedures

    Statements

    Statement

    PreparedStatement

    CallableStatement

  • 8/11/2019 16. Jdbc&SQL Pack

    9/19

    9

    Statements and Queries

    The Statementclass can be used as follows, to

    execute a query

    executeQuery()executes a SQL query, and

    returns a ResultSet

    try {

    Statement stmt = conn.createStatement();ResultSet rset = stmt.executeQuery

    ("select ENAME, SAL from EMP");

    }

    catch (SQLException e) {}

  • 8/11/2019 16. Jdbc&SQL Pack

    10/19

    10

    Processing Query Results

    ResultSetholds a table of result data returned

    by a SQL query

    Support for cursors

    Cursor starts at beginning of data set Use next()to move to next record

    Retrieve data using getXXX()methods, mapping

    results to equivalent Java types

  • 8/11/2019 16. Jdbc&SQL Pack

    11/19

    11

    Processing Results: Example

    try {

    ResultSet rset = stmt.executeQuery(

    "select ENAME, SAL from EMP");

    while (rset.next()) {

    String ename = rset.getString(1);BigDecimal sal = rset.getBigDecimal(2, 2);

    // Can also access columns by name:

    // String ename = rset.getString("ENAME");

    // BigDecimal sal = rset.getBigDecimal("SAL");

    }

    }

    catch (SQLException e) {}

    Obt i i M t d t

  • 8/11/2019 16. Jdbc&SQL Pack

    12/19

    12

    Obtaining ResultSetMetadata

    ResultSetcan be used to get a

    ResultSetMetaDataobject

    Provides result set metadata

    try {

    ResultSet rset = ;ResultSetMetaData md = rset.getMetaData();

    while (rset.next()) {

    for (int i = 0; i < md.getColumnCount(); i++) {

    String lbl = md.getColumnLabel();

    String typ = md.getColumnTypeName(); }

    } catch (SQLException e) {}

  • 8/11/2019 16. Jdbc&SQL Pack

    13/19

    13

    Mapping Database Typesto Java Types

    ResultSetmaps

    database types

    to Java types

    ResultSet rset = stmt.executeQuery

    ("select EMPNO, ENAME, HIREDATE from EMP");

    BigDecimal empno = rset.getBigDecimal(1, 2);

    String ename = rset.getString(2);Date hiredate = rset.getDate(3);

    Col Name

    EMPNO

    ENAME

    HIREDATE

    Type

    NUMBER

    VARCHAR2

    DATE

    P d S

  • 8/11/2019 16. Jdbc&SQL Pack

    14/19

    14

    Prepared Statements

    If you need to execute a statement several times,

    with different bind variables:

    Use a PreparedStatementobject

    Identify bind variables with a ?sign

    try {

    Connection conn = DriverManager.getConnection();

    PreparedStatement pstmt =conn.prepareStatement("update EMP set SAL = ?");

    } catch (SQLException e) {}

    Bi di V i bl d E ti

  • 8/11/2019 16. Jdbc&SQL Pack

    15/19

    15

    Binding Variables and Executing aPreparedStatement

    Specify bind variables using themethods setXXX()inPreparedStatement

    try {

    PreparedStatement pstmt =

    conn.prepareStatement("update EMP set SAL = ?");

    pstmt.setBigDecimal(1, new BigDecimal(55000));

    pstmt.executeUpdate();

    pstmt.setBigDecimal(1, new BigDecimal(65000));

    pstmt.executeUpdate();

    } catch (SQLException e) {}

    T ti

  • 8/11/2019 16. Jdbc&SQL Pack

    16/19

    16

    Transactions

    Transactions are governed by the autoCommit

    property in Connection

    trueinitially, causing a separate transaction per SQL

    statement

    If you want to take control:

    Connection conn = DriverManager.getConnection();

    conn.setAutoCommit(false); // No autocommits now

    // Issue SQL statements

    conn.commit(); or // Commit transaction

    conn.rollback(); // Rollback transaction

  • 8/11/2019 16. Jdbc&SQL Pack

    17/19

    C lli St d P d

  • 8/11/2019 16. Jdbc&SQL Pack

    18/19

    Calling Stored Procedures

    getSal(v_ename in varchar2, v_job out varchar2)

    return numeric

    CallableStatement cs =

    conn.prepareCall( "{? = call getSal(?,?)}" );

    cs.registerOutParameter(1, Types.NUMERIC);

    cs.setString(2, "smith");

    cs.registerOutParameter(3, Types.VARCHAR);

    cs.executeUpdate();

    System.out.println("Smith makes " + cs.getFloat(1) +

    " as a " + cs.getString(3));

  • 8/11/2019 16. Jdbc&SQL Pack

    19/19

    19

    Summary

    JDBC provides classes and interfaces for

    database connectivity

    Connect to a database

    Perform DML and DDL operations

    Prepared statements and stored procedures