+ All Categories
Home > Engineering > Advanced JAVA

Advanced JAVA

Date post: 20-Jan-2017
Category:
Upload: rajvi-vaghasiya
View: 36 times
Download: 0 times
Share this document with a friend
38
Advanced JAVA PREPARED BY : Bhumi Aghera Monika Dudhat Radhika Talaviya Rajvi Vaghasiya JDBC Programming
Transcript
Page 1: Advanced JAVA

Advanced JAVA

PREPARED BY: Bhumi AgheraMonika Dudhat

Radhika TalaviyaRajvi Vaghasiya

JDBC Programming

Page 2: Advanced JAVA

Content

• The JDBC Connectivity Model• Database Programming:• Connecting to the Database• Creating SQL Query• Getting the Results• Updating Database Data• Error Checking and SQLException Class

• The SQL Warning Class

Page 3: Advanced JAVA

Introduction to JDBC

• JDBC - Java Database Connectivity. • JDBC provides API or Protocol to interact with different databases. • With the help of JDBC driver we can connect with different types of databases. • Driver is must needed for connection establishment with any database. • A driver works as an interface between the client and a database server.• JDBC have so many classes and interfaces that allow a java application to send request made

by user to any specific DBMS(Data Base Management System). • JDBC supports a wide level of portability. JDBC provides interfaces that are compatible with

java application.

Page 4: Advanced JAVA

Components of JDBC

• JDBC has four main components and with the help of these components java application can connect with database. i. The JDBC API - it provides various methods and interfaces for easy communication

with database. ii. The JDBC Driver Manager - it loads database specific drivers in an application to

establish connection with database. iii. The JDBC test suite - it will be used to test an operation being performed by JDBC

drivers. iv. The JDBC-ODBC bridge - it connects database drivers to the database.

Page 5: Advanced JAVA

JDBC Specification

• Different version of JDBC has different specification. i. JDBC 1.0 - it provides basic functionality of JDBC. ii. JDBC 2.0 - it provides JDBC API(JDBC 2.0Core API and JDBC 2.0 Optional Package

API). iii. JDBC 3.0 - it provides classes and interfaces in two packages(java.sql and javax.sql).iv. JDBC 4.0 - it provides so many extra features like Auto loading of the driver interface.

Page 6: Advanced JAVA

JDBC Architecture

• JDBC API provides classes and interfaces to handle request made by user and response made by database.

• Some of the important JDBC API are as follow.

DriverManager DriverConnection StatementPreparedStatement

CallableStatementResultSet DatabaseMetaDataResultSetMetaData

Page 7: Advanced JAVA

JDBC Architecture

• Here The Driver Manager plays an important role in JDBC architecture. • It uses some database specific drivers to communicate our J2EE application to database. • As per the diagram first of all we have to program our application with JDBC API. • With the help of Driver Manager class than we connect to a specific database with the help of

specific database driver. • Java drivers require some library to communicate with the database. • We have four different types of java drivers.• Some drivers are pure java drivers and some are partial. So with this kind of JDBC

architecture we can communicate with specific database.

Page 8: Advanced JAVA

JDBC Driver Types

• There are four categories of drivers by which developer can apply a connection between Client (The JAVA application or an applet) to a DBMS. i. Type 1 Driver : JDBC-ODBC Bridge. ii. Type 2 Driver : Native-API Driver (Partly Java driver).iii. Type 3 Driver : Network-Protocol Driver(Pure Java driver for database Middleware). iv. Type 4 Driver : Native-Protocol Driver(Pure Java driver directly connected to database).

Page 9: Advanced JAVA

Type 1 Driver: JDBC-ODBC Bridge• The JDBC type 1 driver which is

also known as a JDBC-ODBC Bridge is a convert JDBC methods into ODBC function calls.

• Sun provides a JDBC-ODBC Bridge driver by ‘sun.jdbc.odbc.JdbcOdbc Driver’.

• The driver is a platform dependent because it uses ODBC which is depends on native libraries of the operating system and also the driver needs other installation for example, ODBC must be installed on the computer and the database must support ODBC driver.

Page 10: Advanced JAVA

Type 1 Driver: JDBC-ODBC Bridge• Type 1 is the simplest compare to all other driver but it’s a platform specific i.e. only on

Microsoft platform. • The JDBC-ODBC Bridge is use only when there is no PURE-JAVA driver available for a

particular database.• Process: Java Application → JDBC APIs → JDBC Driver Manager → Type 1 Driver →

ODBC Driver → Database library APIs → Database• Advantage:

i. Connect to almost any database on any system, for which ODBC driver is installed. ii. It’s an easy for installation as well as easy to use as compare the all other driver.

• Disadvantage: i. The ODBC Driver needs to be installed on the client machine. ii. It’s a not a purely platform independent because its use ODBC which is depends on

native libraries of the operating system on client machine. iii. Not suitable for applets because the ODBC driver needs to be installed on the client

machine.

Page 11: Advanced JAVA

Type 2 Driver: Native-API Driver (Partly Java driver)

• The JDBC type 2 driver is uses the libraries of the database which is available at client side and this driver converts the JDBC method calls into native calls of the database so this driver is also known as a Native-API driver. 

• Process: Java Application → JDBC APIs → JDBC Driver Manager → Type 2 Driver → Vendor Client Database library APIs → Database

Page 12: Advanced JAVA

Type 2 Driver: Native-API Driver (Partly Java driver)

• Advantage:i. There is no implantation of JDBC-ODBC Bridge so it’s faster than a type 1 driver;

hence the performance is better as compare the type 1 driver(JDBC-ODBC Bridge).• Disadvantage:

i. On the client machine require the extra installation because this driver uses the vendor client libraries.

ii. The Client side software needed so can not use such type of driver in the web-based application.

iii. Not all databases have the client side library.iv. This driver supports all JAVA applications except applets. 

Page 13: Advanced JAVA

Type 3 Driver: Network-Protocol Driver

• The JDBC type 3 driver uses the middle tier (application server) between the calling program and the database and this middle tier converts JDBC method calls into the vendor specific database protocol and the same driver can be used for multiple databases also so it’s also known as a Network-Protocol driver as well as a JAVA driver for database middleware.

Page 14: Advanced JAVA

Type 3 Driver: Network-Protocol Driver• Process: Java Application → JDBC APIs → JDBC Driver Manager → Type 3 Driver →

Middleware(Server)→ any Database• Advantage:

i. There is no need for the vendor database library on the client machine because the middleware is database independent and it communicates with client.

ii. Type 3 driver can be used in any web application as well as on internet also because there is no any software require at client side.

iii. A single driver can handle any database at client side so there is no need a separate driver for each database.

iv. The middleware server can also provide the typical services such as connections, auditing, load balancing, logging etc.

• Disadvantage: i. An Extra layer added, may be time consuming. ii. At the middleware develop the database specific coding, may be increase complexity.

Page 15: Advanced JAVA

Type 4 Driver: Native-Protocol Driver

• The JDBC type 4 driver converts JDBC method calls directly into the vendor specific database protocol and in between do not need to be converted any other formatted system so this is the fastest way to communicate quires to DBMS and it is completely written in JAVA because of that this is also known as the “direct to database Pure JAVA driver”.

Page 16: Advanced JAVA

Type 4 Driver: Native-Protocol Driver

• Process: Java Application → JDBC APIs → JDBC Driver Manager → Type 4 Driver (Pure JAVA Driver) → Database Server

• Advantage: i. It’s a 100% pure JAVA Driver so it’s a platform independence.ii. No translation or middleware layers are used so consider as a faster than other drivers. iii. The all process of the application-to-database connection can manage by JVM so the

debugging is also managed easily.• Disadvantage:

i. There is a separate driver needed for each database at the client side.ii. Drivers are Database dependent, as different database vendors use different network

protocols.

Page 17: Advanced JAVA

Connecting to Database• After installing the appropriate driver, next step is to establish a database connection using

JDBC.• There are four steps to establish a JDBC connection as follows:1. Import JDBC Packages: Add import statements to Java program to import required classes

in Java code.

2. Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill user’s JDBC requests.

3. Database URL Formulation: This is to create a properly formatted address that points to the database to which user wish to connect.

4. Create Connection Object: Finally, code a call to the DriverManager object's getConnection method to establish actual database connection.

Page 18: Advanced JAVA

Connecting to Database

1. Import JDBC Packages:• The Import statements tell the Java compiler where to find the classes we reference in our

code and are placed at the very beginning of source code.• To use the standard JDBC package, which allows to select, insert, update, and delete data in• SQL tables, following imports are used in source code :

import java.sql.* ; // for standard JDBC program simport java.m ath.* ; // for BigDecim al and BigInteger support

Page 19: Advanced JAVA

Connecting to Database

2. Register JDBC Driver• Registering the driver is the process by which the driver's class file is loaded into the

memory, so it can be utilized as an implementation of the JDBC interfaces.• We need to do this registration only once in program.• The Class.forName() method is used to load the JDBC driver.• The driver is loaded by calling the Class.forName() method and passing it the name of driver,

as shown as follows:

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Page 20: Advanced JAVA

Connecting to Database

3. Database URL Formulation :• The data source that the JDBC component will connect to defined using the URL format.• The URL consist of three parts:• jdbc: which indicates that the JDBC protocol is to be used to read the URL.• <subprotocol>: which is the jdbc driver name.• <subname>:which is the name of the database.

• Connecting to a database using only the URL:String url = “jdbc:odbc:Information”;Connection con;Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); con = DriverManager.getConnection(url);

Page 21: Advanced JAVA

Connecting to Database

4. Create Connection Object: • Database limit access to authorized user and require the web server to supply a user ID and

password with the request to access the database.• In this case, the Java component uses the (String url, String user, String password) method as

shown below:

String url = “jdbc:odbc:Information”;String userID = “jim”;String password = “keogh”;Connection con;Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); con = DriverManager.getConnection(url, UserID, password);

Page 22: Advanced JAVA

Creating SQL Query

• Passing Queries to database:

Statement stmt = con.createStatement();String str1 = “CREATE TABLE Product(Name VARCHAR(10), Quantity INT)”;stmt.executeUpdate(str1);stmt.close();

Statement stmtin1 = conn.createStatement();String str2 = “INSERT INTO Fruit VALUES(‘Soap', 50)”;stmtin1.executeUpdate(str2);stmtin1.close();

Page 23: Advanced JAVA

Update date into database

• In order to update the database you need to use a statement. but, instead of calling the executeQuery() method, you call the executeUpdate() method.

• There are two types of updates which can perform on database:1. Update record value2. Delete records

• The executeUpdate() method is us for both of these types of updates.1. Updating Records:

The rowsAffected returned by the statement.executeUpdate(sql) call, tells how many records in the database were affected by the SQL statement. For example,

statement statement = connection.createStatement(); String sql = “update people set name=‘john’ where id=123”; int rowsAffected = statement.executeUpdate(sql);

Page 24: Advanced JAVA

Update date into database

2. Deleting Records:The rowsAffected returned by the statement.executeUpdate(sql) call, tells how many

records in the database were affected by the SQL statement.

Example: Statement statement = connection.createStatement(); String sql = “delete from people where id=123”; int rowsAffected = statement.executeUpdate(sql);

Page 25: Advanced JAVA

Get ResultSet

• Example of Getting ResultSet

String queryLehigh = "select * from Lehigh";ResultSet rs = Stmt.executeQuery(queryLehigh);

while (rs.next()){

int ssn = rs.getInt("SSN");String name = rs.getString("NAME");int marks = rs.getInt("MARKS");

}

Page 26: Advanced JAVA

Create ResultSet:

• ResultSet is Created by the two type:1. Using Statement

Statement sta= connection.createStatement();ResultSet result=statement.executeQuery(“select * from people”);

2. Using preparedStatement:String sql=“select * from people”;PraparedStatement statement = connection.praparedStatement(sql);ResultSet result = statement.executeQuery();

Page 27: Advanced JAVA

ResultSet Types

• There are three ResultSet Types:1. ResultSet.TYPE_FORWARD_ONLY2. ResultSet.TYPE_SCROLL_INSENSITIVE3. ResultSet.TYPE_SCROLL_SENSITIVE

• The default type is TYPE_FORWARD_ONLY

Page 28: Advanced JAVA

TYPE_FORWARD_ONLY

• TYPE_FORWARD_ONLY means that the ResultSet can only be navigated forward. That is, we can move from row 1, to row 2, to row 3 etc. It cannot move backwards is the ResultSet.

• Example:

Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);

String query = “select students, grade from class where type=‘FY’;ResultSet rs = stmt.executeQuery( query );while ( rs.next() ){

int grade = rs.getInt(“grade”);rs.updateInt(“grade”, grade+10);rs.updateRow();

}

Page 29: Advanced JAVA

TYPE_SCROLL_INSENSITIVE• TYPE_SCROLL_INSENSITIVE means that the ResultSet can be navigated both forward

and backwards. You can also jump to a position relative to the current position, or jump to an absolute position. The ResultSet is insensitive to changes in the underlying data source while the ResultSet is open.

• Example: Statement stmt = con.createStatement

(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); String query = “select students from class where type=‘not sleeping’ “; ResultSet rs = stmt.executeQuery( query ); rs.previous(); / / go back in the RS rs.relative(-5); / / go 5 records back rs.relative(7); / / go 7 records forward rs.absolute(100); / / go to 100th record

Page 30: Advanced JAVA

TYPE_SCROLL_SENSITIVE

• TYPE_SCROLL_SENSITIVE means that the ResultSet can be navigated both forward and backwards. You can also jump to a position relative to the current position, or jump to an absolute position. The ResultSet is sensitive to changes in the underlying data source while the ResultSet open.

• Example:

Statement stmt = con.createStatement (ResultSet. TYPE_SCROLL_SENSITIVE ResultSet.CONCUR_READ_ONLY);String query = “select students from class where type=‘not sleeping’ “;ResultSet rs = stmt.executeQuery( query );rs.previous(); / / go back in the RS rs.relative(-5); / / go 5 records backrs.relative(7); / / go 7 records forwardrs.absolute(100); / / go to 100th record

Page 31: Advanced JAVA

Handling Errors

• When using the Microsoft JDBC Driver for SQL Server, all database error conditions are returned to your Java application as exceptions using the SQLServerException class.

• The following methods of the SQLServerException class are inherited from java.sql.SQLException and java.lang.Throwable; and they can be used to return specific information about the SQL Server error that has occurred: 1. getSQLState returns the standard X/Open or SQL99 state code of the exception.2. getErrorCode returns the specific database error number.3. getNextException returns the next SQLServerException object or null if there are no

more exception objects to return.4. getMessage returns the full text of the exception. The error message text describes the

problem, and frequently includes placeholders for information, such as object names, that are inserted in the error message when it is displayed.

Page 32: Advanced JAVA

SQL Exception Class• The exception that is thrown when SQL Server returns a warning or error. This class cannot

be inherited.Namespace:   System.Data.SqlClientAssembly: System.Data (in System.Data.dll)

• Inheritance HierarchySystem.Object  System.Exception    System.SystemException      System.Runtime.InteropServices.ExternalException        System.Data.Common.DbException          System.Data.SqlClient.SqlException

• Syntax:[SerializableAttribute]public sealed class SqlException : DbException

Page 33: Advanced JAVA

SQL Exception ClassProperties:

Name DescriptionClass Gets the severity level of the error returned from the .NET Framework Data Provider

for SQL Server.ClientConnection Represents the client connection ID. Data Gets a collection of key/value pairs that provide additional user-defined information

about the exception.ErrorCode Gets the HRESULT of the error.Errors Gets a collection of one or more SqlError objects that give detailed information about

exceptions generated by the .NET Framework Data Provider for SQL Server.HelpLink Gets or sets a link to the help file associated with this exception.HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific

exception.

Page 34: Advanced JAVA

SQL Exception ClassMethods:

Name DescriptionEquals(Object) Determines whether the specified object is equal to the current

object.(Inherited from Object.)GetBaseException() When overridden in a derived class, returns the Exception that is the

root cause of one or more subsequent exceptions.GetHashCode() Serves as the default hash function.GetObjectData(SerializationInfo,StreamingContext)

Sets the SerializationInfo with information about the exception.

GetType() Gets or sets a link to the help file associated with this exception.Tostring() Returns a string that represents the current SqlException object, and

includes the client connection ID

Page 35: Advanced JAVA

SQL Warning Classjava.lang.Object | +--java.lang.Throwable | +--java.lang.Exception | +--com.mimer.jdbc.SQLException | +--com.mimer.jdbc.SQLWarning

All Implemented Interfaces: java.io.Serializable

Direct Known Subclasses: DataTruncation

Page 36: Advanced JAVA

SQL Warning ClassConstructor:

Name DescriptionSQLWarning() Represents the client connection ID. SQLWarning(java.lang.String reason)

Gets a collection of key/value pairs that provide additional user-defined information about the exception.

SQLWarning(java.lang.String reason, java.lang.String SQLstate)

Gets the HRESULT of the error.

SQLWarning(java.lang.String reason, java.lang.String SQLstate, int vendorCode)

Gets a collection of one or more SqlError objects that give detailed information about exceptions generated by the .NET Framework Data Provider for SQL Server.

Page 37: Advanced JAVA

SQL Warning ClassMethod:

Name DescriptiongetNextWarning() Retrieves the warning chained to this SQLWarning

object. setNextWarning(SQLWarning w) Adds an SQLWarning object to the end of the chain.

Page 38: Advanced JAVA

Thank You


Recommended