0% found this document useful (0 votes)
13 views

Day 6-Java-Jdbc and Annotations

Java-Jdbc and Annotations

Uploaded by

77rccbgkqb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Day 6-Java-Jdbc and Annotations

Java-Jdbc and Annotations

Uploaded by

77rccbgkqb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Deloitte

Training
2016

FOUNDATION TRAINING
Java
1
Deloitte Training 2016

JDBC and Annotations


Day 6

3
Objectives of Day 6 Deloitte Training 2016

At the end of this module, you will be able to:

 Perform all database operations through Java


 Use Annotations

4
JDBC
Introduction
 JDBC is a Java Database Connectivity API that lets user access
virtually any tabular data source from a Java application.
 Additionally provides connectivity to a wide range of SQL
databases, and allows user to access other tabular data sources
such as spreadsheets or flat files.
 JDBC defines a low-level API designed to support basic SQL
functionality independently of any specific SQL implementation.
This means the focus is on executing raw SQL statements and
retrieving their results.
 JDBC is based on the X/Open SQL Call Level Interface, an
international standard for programming access to SQL databases.
 The JDBC 2.0 API includes two packages: java.sql, known as the
JDBC 2.0 core API; and javax.sql, known as the JDBC Standard
Extension. Together, they contain the necessary classes to develop
database applications using Java. 6
contd..
 As a core of the Java 2 Platform, the JDBC is available on any
platform running Java.
 The JDBC 3.0 Specification, released in October 2001, introduces
several features, including extensions to the support of various
data types, additional MetaData capabilities, and enhancements to
a number of interfaces.
 JDBC – a module of jdk, provides for backend database
connectivity.
 Java is linked with backend database through JDBC driver.

 JDBC Driver – A software component that enables a Java


application to interact with a database.
 JDBC driver works in two steps

 provides Connection with the database

 implements the protocol for transferring the query and


result between the client and the database.
Two-Tier Model
 The JDBC API supports both two-tier model for database access.
JDBC can either be used directly from an application or as part of
a middle-tier server application.
 Here in a Java application interacts directly with the database.
 Functionality is divided into these two layers:
 Application layer, including the JDBC driver, business logic,
and user interface
 Database layer, including the RDBMS
 The interface to the database is handled by a JDBC driver
appropriate to the particular database management system being
accessed.
 The JDBC driver passes SQL statements to the database and
returns the results of those statements to the application.
contd..
 Type 1
 The Type 1 driver is known as the
End -User JDBC–ODBC Bridge driver.
JDBC Driver Manager
 The driver converts JDBC function
calls into ODBC function calls.
JDBC – ODBC Bridge  The driver is platform dependent.
 It needs to be installed on the
ODBC Driver client machine.
 Not suitable for applets.

Data Base
contd..
 Type 2
 The Type 2 driver is known as the
End-User Native–API driver.
 Uses the client side libraries of
JDBC Driver Manager
the database.
 The driver converts JDBC method
Native API Driver calls into native calls of database
API.
 The driver is platform dependent.
Data Base  It needs to be installed on the client
machine.
 Not suitable for applets.
contd..
 Type 3  The Type 3 driver is known as the
End -User Network Protocol driver.
 The driver converts JDBC function
JDBC Driver Manager
calls into ODBC function calls.
 It makes use of a middle ware that
Network Protocol Driver converts JDBC method calls into
vendor specific database calls.
Middleware  Same driver can be used for
(Application Server) multiple vendors.
 Type 3 is platform independent.
 Can be used on inter net as no
Data Base Data Base
client side software is needed.
contd..
 Type 4  The Type 4 driver is known as the
End -User Native Protocol driver. It is also
known as direct to database pure
JDBC Driver Manager
Java driver.
Native-Protocol Driver
 The driver is platform independent.
 Does not need associated software to
work.

Data Base
contd..
 Steps in using JDBC
1. Load the driver
2. Define the Connection URL
3. Establish the Connection.
4. Create a Statement Object
5. Execute the query
6. Close the connection
contd..
1. Load the driver – the Driver is loaded using the method
forName().
2. Define the Connection URL – the URL is defined as the
String object.
3. Establishing the Connection – the Connection is established
using the Connection object.
4. Creating the Statement – the statement is created using the
Statement
5. Execute the Query
6. Close the connection – the connection is closed using the
close() method.
contd..
 The JDBC API defines standard mappings between SQL
data types and Java/JDBC data types, including support for
SQL99 advanced data types such as BLOBs and CLOBs,
ARRAYs, REFs, and STRUCTs.
contd..
 Sun defines the following levels of JDBC compliance:
 JDBC 1.0 API Compliance, which requires implementation of
the following interfaces:
 java.sql.Driver
 java.sql.DatabaseMetaData
 java.sql.ResultSetMetaData
 java.sql.Connection
 java.sql.Statement
 java.sql.CallableStatement
 java.sql.PreparedStatement
 java.sql.ResultSet
 JDBC 2.0 API Compliance, requires –
 JDBC 1.0 API compliance
 Full implementation of the DatabaseMetaData interface
extensions defined in JDBC 2.0
 Implementation of additional JDBC 2.0 ResultSet methods
contd..
 Connection – provides for a connection (session) with a specific
database.
 Statement – provides for the object used for executing a static
SQL statement and returning the results it produces.
 PreparedStatement – A PreparedStatement is a SQL statement
that is precompiled and stored in a PreparedStatement object.
This object can then be used to execute this statement multiple
times.
 CallableStatement – CallableStatement is used to execute SQL
stored procedures. CallableStatements are created by the method
prepareCall().
 ResultSet – provides for a table of data representing a database
result set, which is usually generated by executing a statement that
queries the database.
contd..
 Methods of Connection interface
 void close() – releases the Connection object's database and JDBC
resources immediately
 void commit() – makes all changes made since the previous
commit/rollback permanent; releases any database locks currently
held by this Connection object.
 Statement createStatement() – Creates a Statement object for
sending SQL statements to the database.
 Statement createStatement (int resultSetType,
int resultSetConcurrency) – Creates a Statement object that will
generate ResultSet objects with the given type and concurrency.
 Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability) – Creates a
Statement object that will generate ResultSet objects with the
given type, concurrency, and holdability.
contd..
 Statement interface
 ResultSet executeQuery(String sql) – Executes the given SQL
statement, which returns a single ResultSet object.
 int executeUpdate(String sql) – Executes the given SQL
statement, which may be an INSERT, UPDATE, or DELETE
statement or an SQL statement that returns nothing, such as
an SQL DDL statement.
 ResultSet execute(String sql) – Executes a SQL statement
that may return multiple results.
contd..
 ResultSet Interface
 Statement getStatement() – Retrieves the Statement object
that produced this ResultSet object.
 String getString(String columnName) – Retrieves the value
of the designated column in the current row of this
ResultSet object as a String in the Java programming
language.
contd..
 java.sql classes
 DriverManager – provides for the basic service for managing a set of
JDBC drivers.
 Methods of DriverManager
o static Connection getConnection(String url) – Attempts to establish
a connection to the given database URL.
o static Connection getConnection(String url, Properties info) –
Attempts to establish a connection to the given database URL.
o static Connection getConnection(String url, String user, String
password) – establishes a connection to the given database URL.
o static Driver getDriver(String url) – locates a driver that understands
the given URL.
o static Enumeration getDrivers() – Retrieves an Enumeration with
all of the currently loaded JDBC drivers to which the current caller
has access.
Batch Updates
 A batch update is a set of update statements submitted to the
database for processing as a batch. This is more efficient than
sending update statements separately. Support for batch updates
is part of the JDBC 2.0 API.
 Under the JDBC 2.0 API, the Statement, PreparedStatement and
CallableStatement support a batch list, which may contain
statements for updating, inserting, or deleting a row.
 The batch list may also contain DDL statements such as
CREATE TABLE and DROP TABLE.
 Only statements that produce an update count can be used in a
batch update. Statements that return a ResultSet object, such as a
SELECT statement, cannot be used in a batch.

22
contd..
 Commands used to manage batch updates include the following:
 AddBatch (add SQL commands to the batch list)
 clearBatch (empty the batch list)
 executeBatch (execute all statements in the list as a batch)
 The batch list associated with a Statement is initially empty.
 The code for inserting new rows as a batch might look like this:
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO CUSTOMERS VALUES('Hoer', 'Simpson')");
stmt.addBatch("INSERT INTO CUSTOMERS VALUES('Bart', 'Simpson')");
stmt.addBatch("INSERT INTO CUSTOMERS VALUES('Marge', 'Simpson')");
int [] updateCounts = stmt.executeBatch();
con.commit();

23
Annotations
 Annotation is supplementary information embedded into the
source file, which is used by various tools during development and
deployment.
 provides for compiler generated boilerplate code.
 do not change the actions of the program.
 ensure the consistency between classes,
 can check the validity of the parameters passed by the clients at run-
time.
 Annotation is created using the interface based mechanism.
Annotations consist of method declarations, which act much as
data members.
@ Retention(RetentionPolicy.RUNTIME)
@ interface exampleanno
{ String str();
int val(); }
contd..
 When an annotation is applied the members are given the values.
 @exampleanno ( str = “CoreJava”, val = 25 )

public static void samp()


{ …………………..
…..}
 An annotation can annotate any declaration viz.. class, interface,
methods, constructors, fields, parameters and enum constants
and other annotations.
 All annotations automatically extend the interface Annotation
belonging to package java.lang.annotation.
contd..
 Retention Policy – determines at what point an annotation is
discarded.
 three retention policies. – SOURCE, CLASS and RUNTIME.
RUNTIME retention offers highest persistence.
 the default policy of CLASS is used.
 A retention policy is specified for an annotation by using one
of Java’s built-in annotations.
contd..
 Using default values – Annotation members are given default
values, which are used if no value is specified.
 @ interface exampleanno {

String str() default "Testing";


int val() default 9000; }
 @exampleanno() // both str and val default

 @exampleanno(str = "some string") // val defaults

 @exampleanno(val = 100) // str defaults

 @exampleanno(str = "Testing", val = 100) // no defaults

 Marker Annotations – are empty annotations. Used in situations


where only declarations are needed.
 @Retention(RetentionPolicy.RUNTIME)

 @interface sampleanno { }
contd..
 Single member annotations – are the ones which contain only
one member. The advantage being that when applied the name of
the member need not be mentioned.
 The name of the member must be value.
 Rules of annotations usage –
 Annotations cannot inherit another annotation.
 All methods declared inside annotation must be without
parameters and the methods cannot be generic.
 Annotation methods cannot specify a throws clause.
 Annotation methods must return one of the following –
√ A primitive type, such as int or double
√ An object of type String, Class, enum type
√ Another annotation type
√ An array of one of the preceding types
Summary Deloitte Training 2016

You have learned how to:


 The various drivers of JDBC

 The JDBC API

 Write programs to connect to the database and perform


various database operations through Java.
 The concept of Annotation

29

You might also like