Вы находитесь на странице: 1из 19

Session 4

JDBC(Contd.)

IETE

Objectives:
Steps of JDBC Code. Statement. ResultSet.

Prepared Statement.
Callable Statement.

IETE

Seven basic steps in using JDBC


1. Load

the driver.

2. Define the Connection URL 3. Establish the Connection 4. Create a Statement object 5. Execute a query 6. Process the results 7. Close the connection
IETE

JDBC Step 1: Load the Driver


Not required in Java 6 In Java SE 6.0 and later (JDBC 4.0 and later), the driver is loaded automatically. Java 5 and earlier Load the driver class only. The class has a static initialization block that makes an instance and registers it with the DriverManager.
Example:
try
Load Driver Class Register Driver Class

{ Class.forName("com.mysql.jdbc.Driver"); DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); } catch (ClassNotFoundException cnfe) { System.out.println("Error loading driver: " cnfe);
IETE

JDBC Step 2: Define the Connection URL databases Remote


Format is jdbc:vendorName: Address contains hostname, port, and database name. Exact details given by supplier of JDBC driver.
Example:
String host = dbhost.mycompany.com; String dbName = mydb; int port = 1234; String oracleURL = jdbc:oracle:thin@ + host + : + port + : + dbName; String sybaseURL = jdbc:sybase:Tds: + host + : + port + : + ?SERVICENAME= + dbName;
IETE

Connection URL

JDBC Step 3: Establish the Connection


Get the main connection Create an object of connection class to establish a connection by invoking the getConnection() method.
Example:
String username = Scott; String password = Tiger; Connection conn = DriverManager.getConnection(oracleURL, username, password);
Driver Manager

Getting Connection

The purpose of the java.sql.DriverManger class in JDBC is to provide a common access layer on top of different database drivers used in an application.
IETE

JDBC Step 4: Make a Statement


Idea
A Statement is used to send queries or commands Statement types Statement, PreparedStatement, CallableStatement

Details on other types given later


Example:
Statement st = conn.createStatement();
Create Statement

IETE

JDBC Step 5: Execute a Query


Idea
statement.executeQuery("SELECT FROM "); This version returns a ResultSet statement.executeUpdate("UPDATE "); statement.executeUpdate("INSERT "); statement.executeUpdate("DELETE"); statement.execute("CREATE TABLE"); statement.execute("DROP TABLE ");

Example:
String query = select col1, col2 from mytable; ResultSet rs = st.executeQuery(query);
Execute SQL Query
IETE

JDBC Step 6: Process the Result


Important ResultSet methods
Result Handling resultSet.next() Goes to the next row. Returns false if no next row. resultSet.getString("columnName") Returns value of column with designated name in current row, as a String. Also getInt, getDouble, getBlob, etc. resultSet.getString(columnIndex) Returns value of designated column. First index is 1 (according to SQL), not 0 (according to Java). resultSet.beforeFirst() Moves cursor before first row, as it was initially. Also first Also last() and afterLast().

IETE

JDBC Step 6: Process the Result (Cont.)


Assumption
Query was SELECT first, last, address FROM Using column names
while(resultSet.next()) { System.out.printf("First name: %s, last name: %s, address: %s%n",resultSet.getString("first"), resultSet.getString("last"), resultSet.getString("address")); } while(resultSet.next()) { System.out.printf( "First name: %s, last name: %s, address: %s%n", resultSet.getString(1), resultSet.getString(2), resultSet.getString(3)); }
IETE

Result Processing Using

column indices

JDBC Step 7: Close the Connection


Idea When totally done, close the database connection. However, opening a new connection is typically much more expensive than sending queries on existing connections, so postpone this step as long as possible. Closing the connection, statements, etc are the releasing database resources. Example
st.close() conn.close();
Closing the Statement Closing the Connection

IETE

A Simple JDBC application


Load Driver getConnection createStatement execute(SQL) Result handling

yes
More results ? no closeStatment closeConnection

import java.sql.*; public class jdbctest { public static void main(String args[]){ try{ Class.forName("org.postgresql.Driver"); Connection con = DriverManager.getConnection ("jdbc:postgresql://lsir-cispc8:5401/pcmdb", "user", "passwd"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery ("select name, number from pcmtable where number < 2"); while(rs.next()) System.out.println( rs.getString(1) + " (" + rs.getInt(2) + ")"); stmt.close() con.close(); } catch(Exception e){ System.err.println(e); IETE }}}

Retrieving data from a ResultSet


ResultSetobjects provide access to a table -Usually they provide access to the pseudo table that is the result of a
SQL query -ResultSetobjects maintain a cursor pointing to the current row of data -This cursor initially points before the first row and is moved to the first row by the next()method.

Example
ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT"); while ( rs.next( ) ) { String name = rs.getString( "NAME" ); float price = rs.getFloat( "PRICE" ); System.out.println("Name: "+name+", price: "+price); }
IETE

Prepared Statement
The PreparedStatement interface, extending Statement, is used to execute a precompiled SQL statement with or without parameters. It is efficient for repeated execution. A PreparedStatement object is created using the preparedStatement method in the Connection interface. For example PreparedStatement pstmt = connection.prepareStatement ("insert into Student (firstName, mi, lastName) " + "values (?, ?, ?)");
IETE

Transactions
A transaction is a collection of DML statements that are executed as if they are a single operation. Transaction might need to be grouped in situations where multiple updates are needed and the entire set of transactions is to be committed or entire set undone in case of a single failure. Transaction service basically include beginning the transaction, executing the SQL statement that make up the transaction, and either perform a commit on overall success of each SQL statement or rollback the transaction as a whole if one of the SQL statements fails.

IETE

Transactions.
Transaction management in JDBC is handled using the Connection object. When a new connection is opened, the transaction autocommit mode is turn on. To execute multiple SQL statements as part of a single transaction, the auto-commit should be disabled as follows : connection.setAutoCommit(false); Auto-commit mode is turn off, an explicit COMMIT or ROLLBACK should be done to commit any unsaved database changes by commit() and rollback() methods of the connection object.
IETE

CallableStatement
Oracle 8i supports two types of stored procedures, namely, PL/SQL and java. PL/SQL stored procedures are called with in JDBC programs by means of the prepareCall() method. For example.
CallableStatement stproc_stmt = con.prepareCall({call procname});

The input parameter are bound to this instance using the setXXX() methods on the CallableStatement object. The output parameter is bound to this object instance using registerOutParameter() method.

IETE

CallableStatement.
executeUpdate method is used to execute stored procedure. Calling Stored function: The syntax for calling stored function
CallableStatement stproc_stmt = conn.prepareCall({?=call stored Procedure(?,?,?) / function(?,?,?)});

IETE

Q&A

IETE

Вам также может понравиться