What is JDBC

82
What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks commonly associated with database usage: Making a connection to a database Creating SQL or MySQL statements Executing that SQL or MySQL queries in the database Viewing & Modifying the resulting records Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as: Java Applications Java Applets Java Servlets Java ServerPages (JSPs) Enterprise JavaBeans (EJBs) All of these different executables are able to use a JDBC driver to access a database and take advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code. Pre-Requisite: Before progressing on this tutorial you need to have good understanding on the following two subjects: Core JAVA Programming SQL or MySQL Database JDBC Architecture: The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers: JDBC API: This provides the application-to-JDBC Manager connection. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application:

description

jdbc

Transcript of What is JDBC

What is JDBC?JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases!he JDBC library includes APIs for each of the tas"s commonly associated with database usage# $a"ing a connection to a database Creating %&' or $y%&' statements ()ecuting that %&' or $y%&' *ueries in the database +iewing , $odifying the resulting records-undamentally, JDBC is a speci.cation that provides a complete set of interfaces that allows for portable access to an underlying database Java can be used to write di/erent types of e)ecutables, such as# Java Applications Java Applets Java %ervlets Java %erverPages 0J%Ps1 (nterprise JavaBeans 0(JBs1All of these di/erent e)ecutables are able to use a JDBC driver to access a database and ta"eadvantage of the stored dataJDBC provides the same capabilities as 2DBC, allowing Java programs to contain database-independent codePre-Requisite:Before progressing on this tutorial you need to have good understanding on the following twosub3ects# Core JA+A Programming %&' or $y%&' DatabaseJDBC Architecture:!he JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers# JDBC API: !his provides the application-to-JDBC $anager connection JDBC Driver API: !his supports the JDBC $anager-to-Driver Connection!he JDBC API uses a driver manager and database-speci.c drivers to provide transparent connectivity to heterogeneous databases!he JDBC driver manager ensures that the correct driver is used to access each data source !he driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases-ollowing is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application#Common JDBC Components:!he JDBC API provides the following interfaces and classes# DriverManager: !his class manages a list of database drivers $atches connection re*uests from the 3ava application with the proper database driver using communication subprotocol !he .rst driver that recogni4es a certain subprotocol under JDBC will be used to establish a database Connection Driver: !his interface handles the communications with the database server 5ou will interact directly with Driver ob3ects very rarely Instead, you use Driver$anager ob3ects, which manages ob3ects of this type It also abstracts the details associated with wor"ing with Driver ob3ects Connection : !his interface with all methods for contacting a database !he connection ob3ect represents communication conte)t, ie, all communication with database is through connection ob3ect only tatement : 5ou use ob3ects created from this interface to submit the %&' statementsto the database %ome derived interfaces accept parameters in addition to e)ecuting stored procedures Resu!tet: !hese ob3ects hold data retrieved from a database after you e)ecute an %&' *uery using %tatement ob3ects It acts as an iterator to allow you to move throughits data "#$%ception: !his class handles any errors that occur in a database application&he JDBC '() Pac*ages!he 3avas*l and 3ava)s*l are the primary pac"ages for JDBC 67 !his is the latest JDBC version at the time of writing this tutorial It o/ers the main classes for interacting with your data sources!he new features in these pac"ages include changes in the following areas# Automatic database driver loading ()ception handling improvements (nhanced B'2B8C'2B functionality Connection and statement interface enhancements 9ational character set support %&' :2;ID access %&' $' data type support Annotations Structured Query Language (SQL) is a standardized language that allows you to perform operationson a database, such as creating entries, reading content, updating content, and deleting entries. SQL is supported by all most any database you will likely use, and it allows you to write database code independently of the underlying database. This tutorial gies an oeriew of SQL, which is a pre!re"uisite to understand #$%& concepts. Thistutorial gies you enough SQL to be able to Create, Read, Update, and Delete (often referred to as CRUD operations) data from a database. 'or a detailed understanding on SQL, you can read our (ySQL Tutorial. Create Database# The &)*+T* $+T+%+S* statement is used for creating a new database. The synta, is- SQL> CREATE DATABASE DATABASE_NAME; ()ample# The following SQL statement creates a $atabase named *(.- SQL> CREATE DATABASE EMP; Drop Database# The $)/. $+T+%+S* statement is used for deleting an e,isting database. The synta, is- SQL> DROP DATABASE DATABASE_NAME; Note: To create or drop a database you should hae administrator priilege on your database serer.%e careful, deleting a database would loss all the data stored in database. Create !able# The &)*+T* T+%L* statement is used for creating a new table. The synta, is- SQL> CREATE TABLE table_name (column_name column_data_tye!column_name column_data_tye!column_name column_data_tye""" #; ()ample# The following SQL statement creates a table named *mployees with four columns- SQL> CREATE TABLE Emloyee$ (%d &NT NOT N'LL!a(e &NT NOT N'LL!)%*$t +ARC,AR(-..#!la$t +ARC,AR(-..#!PR&MAR/ 0E/ ( %d # #; Drop !able# The $)/. T+%L* statement is used for deleting an e,isting table. The synta, is- SQL> DROP TABLE table_name; ()ample# The following SQL statement deletes a table named *mployees- SQL> DROP TABLE Emloyee$; I9%(:! Data# The synta, for 01S*)T looks similar to the following, where column2, column3, and so on represent the new data to appear in the respectie columns- SQL> &NSERT &NTO table_name +AL'ES (column1! column-! """#; ()ample# The following SQL 01S*)T statement inserts a new row in the *mployees database created earlier- SQL> &NSERT &NTO Emloyee$ +AL'ES (122! 13! 45a*a4! 4Al%4#; %('(C! Data# The S*L*&T statement is used to retriee data from a database. The synta, for S*L*&T is- SQL> SELECT column_name! column_name! """6ROM table_name7,ERE cond%t%on$; The 45*)* clause can use the comparison operators such as 6, 76, 8, 9, 86,and 96, as well as the %*T4**1 and L0:* operators. ()ample# The following SQL statement selects the age, first and last columns from the *mployees table where id column is 2;;- SQL> SELECT )%*$t! la$t! a(e 6ROM Emloyee$ 7,ERE %d 8 122; The following SQL statement selects the age, first and last columns from the *mployees table where first column contains Zara- SQL> SELECT )%*$t! la$t! a(e 6ROM Emloyee$ 7,ERE )%*$t L&0E 495a*a94; ?PDA!( Data# The >>01 methods bind values to the parameters, where >>> represents the Java data type of the value you wish to bind to the input parameter If you forget to supply the values, you will receive an %&'()ception(ach parameter mar"er is referred to by its ordinal position !he .rst mar"er represents position D, the ne)t position I%!% \($P\\get(mp9ame\ [[C:(A!( P:2C(D?:( \($P\\get(mp9ame\ 0I9 ($PEID I9!, 2?! ($PE-I:%! +A:CIA:001 method of the Prepared%tatement or Callable%tatement ob3ect or the :esult%etupdate>>>01 method%&' JDBC8Java set>>> update>>>+A:CIA: 3avalang%tring set%tring update%tringCIA: 3avalang%tring set%tring update%tring'29G+A:CIA: 3avalang%tring set%tring update%tringBI! boolean setBoolean updateBoolean9?$(:IC 3avamathBigDecimal setBigDecimal updateBigDecimal!I95I9! byte setByte updateByte%$A''I9! short set%hort update%hortI9!(G(: int setInt updateIntBIGI9! long set'ong update'ong:(A' Zoat set-loat update-loat-'2A! Zoat set-loat update-loatD2?B'( double setDouble updateDouble+A:BI9A:5 byteQ R setBytes updateBytesBI9A:5 byteQ R setBytes updateBytesDA!( 3avas*lDate setDate updateDate!I$( 3avas*l!ime set!ime update!ime!I$(%!A$P 3avas*l!imestampset!imestamp update!imestampC'2B 3avas*lClobsetClob updateClobB'2B 3avas*lBlobsetBlob updateBlobA::A53avas*lArray setA::A5 updateA::A5:(- 3avas*l:ef %et:efupdate:ef%!:?C! 3avas*l%truct %et%truct update%tructJDBC =7 has enhanced support for B'2B, C'2B, A::A5, and :(- data types !he :esult%et ob3ect now has updateB'2B01, updateC'2B01, updateArray01, and update:ef01 methods that enable you to directly manipulate the respective data on the server!he set>>>01 and update>>>01 methods enable you to convert speci.c Java types to speci.c JDBC data types !he methods, set2b3ect01 and update2b3ect01, enable you to map almost any Java type to a JDBC data type:esult%et ob3ect provides corresponding get>>>01 method for each data type to retrieve column value (ach method can be used with column name or by its ordinal position%&' JDBC8Java set>>> get>>>+A:CIA: 3avalang%tring set%tring get%tringCIA: 3avalang%tring set%tring get%tring'29G+A:CIA: 3avalang%tring set%tring get%tringBI! boolean setBoolean getBoolean9?$(:IC 3avamathBigDecimal setBigDecimal getBigDecimal!I95I9! byte setByte getByte%$A''I9! short set%hort get%hortI9!(G(: int setInt getIntBIGI9! long set'ong get'ong:(A' Zoat set-loat get-loat-'2A! Zoat set-loat get-loatD2?B'( double setDouble getDouble+A:BI9A:5 byteQ R setBytes getBytesBI9A:5 byteQ R setBytes getBytesDA!( 3avas*lDate setDate getDate!I$( 3avas*l!ime set!ime get!ime!I$(%!A$P 3avas*l!imestampset!imestamp get!imestampC'2B 3avas*lClobsetClob getClobB'2B 3avas*lBlobsetBlob getBlobA::A53avas*lArray setA::A5 getA::A5:(- 3avas*l:ef %et:efget:ef%!:?C! 3avas*l%truct %et%truct get%tructDate , !ime Data !ypes#!he 3avas*lDate class maps to the %&' DA!( type, and the 3avas*l!ime and 3avas*l!imestamp classes map to the %&' !I$( and %&' !I$(%!A$P data types, respectively-ollowing e)amples shows how the Date and !ime classes format standard Java date and time values to match the %&' data type re*uirementsimport 3avas*lDateLimport 3avas*l!imeLimport 3avas*l!imestampLimport 3avautilKLpublic class %*lDate!ime N public static void main0%tringQR args1 N88Get standard date and time3avautilDate 3avaDate O new 3avautilDate01Llong 3ava!ime O 3avaDateget!ime01L%ystemoutprintln0P!he Java Date is#P S 3avaDateto%tring011L88Get and display %&' DA!(3avas*lDate s*lDate O new 3avas*lDate03ava!ime1L%ystemoutprintln0P!he %&' DA!( is# P S s*lDateto%tring011L88Get and display %&' !I$(3avas*l!ime s*l!ime O new 3avas*l!ime03ava!ime1L%ystemoutprintln0P!he %&' !I$( is# P S s*l!imeto%tring011L88Get and display %&' !I$(%!A$P3avas*l!imestamp s*l!imestamp Onew 3avas*l!imestamp03ava!ime1L%ystemoutprintln0P!he %&' !I$(%!A$P is# P S s*l!imestampto%tring011L T88end mainT88end %*lDate!ime9ow let us compile above e)ample as follows#C#CJ3avac %*lDate!ime3avaC#CJ;hen you run JDBC()ample, it produces following result#C#CJ3ava %*lDate!ime!he Java Date is#!ue Aug DH D=#6U#7< G$!S76#77