Vous êtes sur la page 1sur 45

JDBC

By Cavalier iT

DATABASE FUNDAMENTALS
Database Database Server Relational Database Keys Normalising SQL Remote Database Access ODBC JDBC

Database server
Software program Manages databases Keeps them organised Provides shared access Physical level and Logical level orgn. Similar to an office assistant.

Relational Database
E.F Codd IBM Mathematician 1960 Tables Columns = type of information Rows = specific records

Keys
Access to info in tables is organized by keys Columns or groups of columns that uniquely identify a row Helps you to decide whether to modify or insert Primary keys Composite keys Foreign keys

Normalising
1 big table ? Many small tables ? Minimize the number of columns Increase data consistency Purpose to remove redundant data & make updation and maintenance easy Trade off between
Data consistency Database size Database performance

SQL
Language for interacting with relational databases
Data Definition Language
Create & Design databases

Data Maintenance Language


Updating data

Data Query Language


Retrieve information from the database

SQL as a DDL
Data Definition Language
Create & Design databases
CREATE DATABASE <database name> CREATE TABLE <table name> (column defn) COLUMN DEFN. => <Col Name> <Col Type> COLUMN TYPE => char(n); int;float; bit; date; time get() of ResultsSet converts SQL dt to Java dt set() of PreparedStatement do vice versa ALTER TABLE <table name> ADD (column definition) Adds a column where the row values are set to null DROP TABLE <table name>

SQL as a DML
Data Maintenance Language
Updates data
INSERT INTO <table name> VALUES ( , , .) INSERT INTO <table name> (column names) VALUES ( , , .) DELETE FROM <table name> WHERE <condition> UPDATE <table name> SET <column =value> WHERE <condition> ORDER BY <column>

SQL as a DQL
Data Query Language
Retrieves information from database
SELECT <column name> FROM <table name> WHERE <condition> ORDER BY <column>

REMOTE DATABASE ACCESS


Databases share access remotely Shared access among many users Database client is required to communicate with Database server. SQL is sent with a Database driver. Results are received with the Database driver. JDBC drivers are used by Java applications and applets that are Database clients.

Open Data Base Connectivity


Scenario prior to ODBC
DBMS was vendor specific
Oracle, IBM etc

Learn the DBMS language to communicate.


SQLNet, DB2

Goal
Access any data from any application regardless of which DBMS

Solution
Driver inserted between application and DBMS which translates application queries into commands the DBMS understands.

WHY JDBC?
ODBC is a C API
Not Object Oriented Uses Pointers Other dangerous programming constructs

ODBC needs to be installed on clients machine


Applet access to database is constrained

JDBC DRIVERS
4 Categories
JDBC-ODBC Native API
Driver talks in RDBMS native protocol Uses binary code + Java Must be preinstalled

bridge + ODBC

ODBC communicates with the RDBMS Java needs to be preinstalled

JDBC-Net
Talks in a std. Network protocol to a Database Access Server Database Access Server uses ODBC to speak to RDBMS.

Native Protocol
Talks the vendor specific protocol of the RDBMS

WORKING WITH JDBC


SQL package Classes and Interfaces of the package Methods of the Classes and Interfaces Sample code

WORKING WITH JDBC


To use JDBC you need
Database server Access Database driver JDBC_ODBC Bridge

Package
java.sql.*;

Classes & Interfaces


DriverManager Class Connection Interface Statement Interface ResultSet Interface ResultSetMetaData Interface DatabaseMetaData Interface

SUMMARISING
Import java.sql.* Register the driver Establish the connection Create the statement Execute the query Traverse the resultset Display the results Close the connection

WORKING WITH JDBC


DriverManager Class
Manages JDBC drivers loaded on your system Driver can be loaded in 2 ways
Class.forName() Setting the jdbc.drivers System property

DriverManager class has no constructors All methods are static Some useful methods are:Enumeration getDrivers() Connection getConnection(String url) Connection getConnection(String url, String ID, String pwd) url= jdbc: subprotocol name: DSN

DriverManager Code
import java.sql.*; import java.util.*; class jdbc{ public static void main(String a[]){ try{ Class.forName("com.mysql.jdbc.Driver"); Enumeration drivers=DriverManager.getDrivers(); System.out.println("Available Drivers"); while(drivers.hasMoreElements(){ Driver d=(Driver)drivers.nextElement();

DriverManager Code
System.out.println("Driver "+d.getClass().getName()); System.out.println("Driver "+d.getMajorVersion()); System.out.println("Driver "+d.getMinorVersion()); System.out.println("Driver "+d.jdbcCompliant()); DriverPropertyInfo prop[]=driver.getPropertyInfo("",null); if(props!=null){ for(int i=0; i<prop.length; ++i){ System.out.println("Name "+prop[i].name); System.out.println("Description"+prop[i].description); System.out.println("Value "+prop[i].value); } } }

DriverManager Code
}catch(Exception e){ System.out.println(e); System.exit(0); } }

WORKING WITH JDBC


Connection Interface
Some useful methods are:close() Closes the connection createStatement() Creates a Statement object prepareStatement() Creates a PreparedStatement object prepareCall() Creates a CallableStatement object getMetaData() Creates an object of DatabaseMetaData If the database support transaction processing commit()

DatabaseMetaData code
import java.sql.*; import java.util.*; class jdbc1{ public static void main(String a[]){ try{ Class.forName("com.mysql.jdbc.Driver"); Connection c=DriverManager.getConnection("jdbc:odbc:DSN"); DatabaseMetaData meta=c.getMetaData(); System.out.println("Database "+meta.getDatabaseProductName()); System.out.println("Version "+meta.getDatabaseProductVersion); System.out.println("User Name "+meta.getUserName()); c.close() }catch(Exception e){ System.out.println(e); System.exit(0); } } }

WORKING WITH JDBC


Statement Interface
Some useful methods are:executeQuery() Executes a SQL statement such as SELECT that queries a database Returns a ResultSet object executeUpdate() Executes a SQL statement such as INSERT, UPDATE, or DELETE that updates a database Returns a integer value of the row count associated with the SQL statement. execute() Executes a SQL statement that is written as a String object Returns a boolean value of whether a ResultSet object was created or not. getResultSet() & getMoreResults()

WORKING WITH JDBC


ResultSet Interface
Provides access to the data returned by a query. ResultSet object maintains a pointer to a row within the tabular results called the cursor. Some useful methods are:boolean next() ResultSetMetaData getMetaData() getColumnCount() getColumnName() getColumnType()

ResultSet + executeQuery()
import java.sql.*; import java.util.*; class jdbc2{ public static void main(String a[]){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection(" jdbc:mysql://localhost/test,root,root "); Statement s=c.createStatement(); ResultSet r=s.executeQuery("Select * from <tablename>"); displayResults(r); c.close(); }catch(Exception e){ System.out.println(e); System.exit(0); } }

ResultSet + executeQuery()
static void displayResults(ResultSet rs) throws SQLException{ ResultSetMetaData rmeta=rs.getMetaData(); int no_of_cols=rmeta.getColumnCount(); for(int i=1; i<=no_of_cols; ++i){ if(i<no_of_cols) System.out.print(rmeta.getColumnName(i)+" | "); else System.out.print(rmeta.getColumnName(i)); }

ResultSet + executeQuery()
while(rs.next()){ for(int i=1; i<=no_of_cols; ++i){ if(i<no_of_cols) System.out.print(rs.getString(i)+" | "); else System.out.print(rs.getString(i).trim()); } } } }

ResultSet code + execute () ..


import java.sql.*; import java.util.*; class jdbc3{ public static void main(String a[]){ if(a.length!=1){ System.out.println("Usage: java jdbc3 sql"); System.exit(0); }

.. ResultSet code + execute () ..


try{ Class.forName("com.mysql.jdbc.Driver"); Connection c=DriverManager.getConnection(" jdbc:mysql://localhost/test,root,root "); Statement s=c.createStatement(); String sql=a[0]; boolean hasResults=s.execute(sql); if(hasResults){ ResultSet r=s.getResultSet(); if(r!=null) displayResults(r); } c.close(); }catch(Exception e){ System.out.println(e); System.exit(0); } }}

.. ResultSet code + execute () ..


static void displayResults(ResultSet rs) throws SQLException{ ResultSetMetaData rmeta=rs.getMetaData(); int no_of_cols=rmeta.getColumnCount(); for(int i=1; i<=no_of_cols; ++i){ if(i<no_of_cols) System.out.print(rmeta.getColumnName(i)+" | "); else System.out.print(rmeta.getColumnName(i)); }

.. ResultSet code + execute ()


while(rs.next()){ for(int i=1; i<=no_of_cols; ++i){ if(i<no_of_cols) System.out.print(rs.getString(i)+" | "); else System.out.print(rs.getString(i).trim()); } }}

Prepared Statements
Extends from statement Takes an SQL at creation time Sent to dbms for precompilation Faster than Statement Capable of taking parameters

Creating a PreparedStatement
prepareStatement() method is invoked on the connection object
PreparedStatement updateSales= con.prepareStatement( UPDATE COFFEES SET SALES=? WHERE COF_NAME LIKE ?);

The ?s represent the placeholders for input parameters

Using Prepared statements


Before executing a prepared statement, all ? Placeholders should be populated. Use an appropriate setXXX() method.
eg., updateSales.setInt(1,75) updateSales.setString(2,colombian)

Then call one of the execute methods.

Some important methods


clearParameters()- clears all the set parameters Execute()- Executes the SQL stmt. executeUpdate()- executes an SQL stmt that updates the database. executeQuery()- executes an SQL stmt that returns a resultset setXXX()-sets the specified parameter.

CallableStatement
Used to call stored procedures Is independent of RDBMS syntax

Creating a stored procedure


The typical syntax for creating a stored procedure will be
create procedure SHOW_SUPPLIERS as select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME from SUPPLIERS, COFFEES where SUPPLIERS.SUP_ID = COFFEES.SUP_ID

Creating a callablestatement
prepareCall() method of connection object is called CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

Calling a procedure
To call a procedure use one of the execute methods of statement interface ResultSet rs = cs.executeQuery();

Creating dynamic resultsets


The createStatement method of connection has been overloaded to take 2 more parameters One parameter to indicate concurrency mode(read-only or updatable) One parameter to indicate direction and dynamism.

Code
Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIV E, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");

TRANSACTION PROCESSING
Transaction consists of a group of related database operations. SQL statements that make up the transaction update the database at the same time. Not committed automatically If an error occurs transaction is rolled back

TRANSACTION METHODS
Connection Interface methods for transaction processing are:supportsTransactions() setAutoCommit() commit() rollback() supportsTransactionIsolation(); getTransactionIsolation() setTransactionIsolation()

SUMMARISING
Import java.sql.* Register the driver Establish the connection Create the statement Execute the query Traverse the resultset Display the results Close the connection

Vous aimerez peut-être aussi