Download - 11. jdbc
Java Database Java Database ConnectivityConnectivity
JDBC
JDBC is an API with set of classes and interfaces present in package java.sql
JAVAJAVA
APPAPP DBSupporting Software
SERVERC L I E N T
SERVER
JAVAJAVA
APPAPP DBDRIVER
C L I E N T
Thick Client
Thin Client
DRIVER
JDBC
JDBCJDBC supports 4 types of Drivers supports 4 types of DriversThick Drivers:
JDBC-ODBC Bridge Driver.JDBC-ODBC Bridge Driver.
Native-API Partly Java DriverNative-API Partly Java Driver
Thin Drivers:
Net-Protocol Fully Java DriverNet-Protocol Fully Java DriverNative-Protocol Fully Java Driver
JDBC-ODBC Bridge Driver (TYPE – I)
JAVA APP
DB
JDBC-ODBC BRIDGE
JDBC
ODBC
C L I E N T
SERVER
JDBC API access via one or more ODBC drivers.Binary code be loaded on each client machine
ODBC
CLIENTCLIENT
ApplicationApplication
DBDRIVER 1
DRIVER 2
DRIVER 3
connection
Request
ODBC Driver Manager
DB
DB
connection
connection
SERVER
The Open Database Connectivity (ODBC) interface by Microsoft allows applications to access data in database management systems (DBMS) using SQL as a standard for accessing the data.
Native-API Partly Java Driver Native-API Partly Java Driver (TYPE – II)
ORACLE
SQL Server
OCI
DB Library
J
D
B
C
JAVA App
C L I E N T SERVER
Binary code should be loaded on each client machineConverts JDBC calls into calls on the client API for all databases
Net-Protocol Fully Java Driver Net-Protocol Fully Java Driver (TYPE – III)
Type 3Type 3DriverDriver
MiddleMiddlewarewareAppliApplicationcation
Type 1Type 1
Type 2Type 2
Type 4Type 4
JAVA JAVA AppApp
DBDB11
DB2DB2
DB3DB3
CLIENT SERVERAPPLICATION SERVER
Protocol 1
The specific protocol used depends on the vendor
Native-Protocol Fully Java Native-Protocol Fully Java DriverDriver(TYPE – IV)
Direct call from the Direct call from the clientclient to the to the DBMS serverDBMS server and is a and is a practical practical solution for Intranet access.solution for Intranet access.protocols are protocols are proprietary to database vendors, proprietary to database vendors, primary primary source for this style of driversource for this style of driver..
JDBCJDBCDriverDriver
JAVAJAVA AppApp
Data Base
PROTOCOL
User Sockets & Streams
JDBC
The 4 steps to connect to database The 4 steps to connect to database are:are:
Loading the Driver.Loading the Driver.
Getting the Connection to database.Getting the Connection to database.
Executing the SQL Query.Executing the SQL Query.
Closing the Connection.Closing the Connection.
Loading DriverLoading Driver
Syntax for loading the Class fileClass.forName(“Driver Class Name”);
Example for Jdbc-Odbc bridge driver:Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Class.forName("oracle.jdbc.driver.OracleDriver");
JDBC drivers by various VendorsJDBC drivers by various Vendors
Jdbc-Odbc Bridge : sun.jdbc.odbc.JdbcOdbcDriver
Oracle : oracle.jdbc.driver.OracleDriver
DB2 : com.ibm.db2.jdbc.app.DB2Driver
Pointbase : com.pointbase.jdbc.JdbcUniversalDriver
Sybase : com.sybase.jdbc2.jdbc.SybDriver
SQL-Server : weblogic.jdbc.mssqlserver4.Driver
Data Source Name (DSN)Data Source Name (DSN)
User DSNUser DSN
Available for user who creates and Available for user who creates and stores in registrystores in registry
System DSNSystem DSN
Available for all users and stores in Available for all users and stores in registryregistry
Various ways of getting database Various ways of getting database connectionconnection
Connection con =DriverManager.getConnection(“jdbc:odbc:dsnname”);
DriverManager.getConnection(“jdbc:odbc:dsnname”, “username”, “password”);
DriverManager.getConnection(“jdbc:oracle:oci”, “username”, “password”);
DriverManager.getConnection(“jdbc:oracle:thin:@ipaddress:port:serviceId”, “username”, “password”)
StatementStatement
StatementIt is used to execute SQL statements
Prepared StatementUsed to prepare statements with place holders(?) to set the values at run time
Callable StatementUsed to execute functions or procedures available in data base
StatementStatement
A Statement object is used for executing a static A Statement object is used for executing a static SQL statement and obtaining the results produced SQL statement and obtaining the results produced by it.by it.
Statement smt = con.createStatement();
ResultSet rs = smt.executeQuery(“Select_Queries”);
int n = smt.executeUpdate(“DML_Queries”);
boolean b = smt.execute(“Any_Query”);
ResultSetResultSet
Is an Object which stores data of the select Is an Object which stores data of the select statement result in statement result in records and fieldsrecords and fields form. form.
By default it is By default it is Forward OnlyForward Only and and Read OnlyRead Only..
Result Set Navigation and updating is possible Result Set Navigation and updating is possible from new API version 1.2 onwards.from new API version 1.2 onwards.
Navigating from one record to anotherNavigating from one record to anotherbooleanboolean b = rs.next()b = rs.next()
Extracting values from ResultSet is possible either by Field Extracting values from ResultSet is possible either by Field Name or Field IndexName or Field Index
intint n=rs.getInt(1);n=rs.getInt(1);oror
intint n = rs.get( n = rs.get(“empID”“empID”););
StringString s=rs.getString(1);s=rs.getString(1);oror
StringString s=rs.getString(s=rs.getString(“empName”“empName”););
ResultSetResultSet
Column Index
Column Name
ResultSetMetaDataResultSetMetaData
It is Data about Data of ResultSet like field names, no.It is Data about Data of ResultSet like field names, no.
of Columns etc.of Columns etc.
ResultSetMetaDataResultSetMetaData rsmd = rs.getMetaData();rsmd = rs.getMetaData();
intint count = rsmd.getColumnCount(); count = rsmd.getColumnCount();
StringString fname = rsmd.getColumnName(int index); fname = rsmd.getColumnName(int index);
StringString dn = rsmd.getColumnTypeName(int index); dn = rsmd.getColumnTypeName(int index);
PreparedStatementPreparedStatement
A PreparedStatement object is used when an application plans to reuse a statement multiple times.The application prepares the SQL Statement it plans to use. Once prepared, the application can specify values for parameters (if any) in the prepared SQL statement.
PreparedStatement ps = con.prepareStatement(“Query with Place Holders”);
Examples:
PreparedStatement ps = con.prepareStatement(“select * from emp where empno=?”);
Place Holder
PreparedStatementPreparedStatement
PreparedStatement ps = con.prepareStatement(“insert into emp (empno,ename) values(?,?)”);
ps.setInt(1,102);ps.setInt(1,102);
ps.setString(2, ps.setString(2, “Scott”“Scott”););
Executing the PreparedStatementResultSet rs=ps.executeQuery();int n=ps.executeUpdate();boolean b=ps.execute();
Set values for place holders
PreparedStatement ps = con.prepareStatement(“insert into emp (empno,ename) values(?,?)”);
ps.setInt(1,102);ps.setInt(1,102);
ps.setString(2, ps.setString(2, “Scott”“Scott”););
Executing the PreparedStatementResultSet rs=ps.executeQuery();int n=ps.executeUpdate();boolean b=ps.execute();
StatementStatement vsvs PreparedStatementPreparedStatement
A A StatementStatement object object Doesn’tDoesn’t contain acontain a SQL statement at the time of creation. SQL statement at the time of creation.Compiled and executed every timeCompiled and executed every time
A A PreparedStatementPreparedStatement object object Is a Is a precompiledprecompiled Statement StatementContains a SQL statement at the time of creation.Contains a SQL statement at the time of creation.Support for Support for Place holdersPlace holders, (, (Ex:Ex: For data type blob, clob, For data type blob, clob, binaryStream)binaryStream)
Function
create or replace function DemoFunction (id number) return varchar2 is
temp varchar2(20);begin select name into temp from Student where rollno=id;
return temp;end DemoFunction;
Procedure
create or replace procedure DemoProcedure(sname varchar2, rno number) isbegin
insert into Student values(sname,rno);end DemoProcedure;
CallableCallableStatementStatement
A A CallableStatementCallableStatement is used to call stored procedures that return is used to call stored procedures that return values. The values. The CallableStatementCallableStatement has methods for retrieving the has methods for retrieving the return values of the stored procedure. return values of the stored procedure.
CallableStatementCallableStatement cs = con.prepareCall( cs = con.prepareCall(“{call “{call prod(?,?)}”prod(?,?)}”););
= con.prepareCall(= con.prepareCall("{?=call "{?=call fun(?)}"fun(?)}"););
Example:Example:
CallableStatementCallableStatement cs = con.prepareCall( cs = con.prepareCall(“{call “{call emp.insert(?,?)}”emp.insert(?,?)}”););
CallableStatementCallableStatement
CallableStatement cs = con.prepareCall(“{?=call
empSal(?)}”);
cs.registerOutParameter(1,cs.registerOutParameter(1, java.sql.Types. java.sql.Types.INTEGER);INTEGER);
cs.setInt(2,102);cs.setInt(2,102);
cs.executeUpdate();cs.executeUpdate();
int result = cs.getInt(1);int result = cs.getInt(1);
CallableStatementCallableStatement
java.sql.Types
java.sql.Types.DATEjava.sql.Types.DOUBLEjava.sql.Types.TIMEjava.sql.Types.FLOATjava.sql.Types.VARCHAR java.sql.Types.INTEGERjava.sql.Types.TIMESTAMP java.sql.Types.NUMERICjava.sql.Types. CHAR java.sql.Types.BOOLEANjava.sql.Types.BLOBjava.sql.Types.CLOB
Example ProgramExample Program
ClassClass.forName(.forName("oracle.jdbc.driver.OracleDriver""oracle.jdbc.driver.OracleDriver"););
ConnectionConnection con = con = DriverManagerDriverManager.getConnection.getConnection("jdbc:oracle:thin:@localhost:15("jdbc:oracle:thin:@localhost:1521:orcl"21:orcl",, "scott" "scott",, "tiger" "tiger"););
CallableStatement CallableStatement cs = con.prepareCall(cs = con.prepareCall("{?=call empSal(?)}""{?=call empSal(?)}"););
cs.setInt(2, 7369);cs.setInt(2, 7369);
cs.cs.registerOutParameterregisterOutParameter(1,(1,Types.Types.INTEGER);INTEGER);
cs.executeUpdate();cs.executeUpdate();
int x=cs.getInt(1);int x=cs.getInt(1);
SystemSystem.out.println(.out.println(" The Value is: "" The Value is: "+ x);+ x);
con.close();con.close();