SlideShare uma empresa Scribd logo
1 de 30
Q5M2 – 3SC Dudy Fathan Ali S.Kom
JDBC
Q5M2 – 3SC
Dudy Fathan Ali, S.Kom (DFA)
2015
CEP - CCIT
Fakultas Teknik Universitas Indonesia
Objectives
Q5M2 – 3SC Dudy Fathan Ali S.Kom
In this session, you will learn to:
Identify the layers in JDBC architecture
Identify the types of JDBC drivers
Use the classes and interfaces of JDBC application programming interface
Understand and execute the steps to create JDBC applications
Database Connectivity
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Sun Microsystems has included JDBC API as a part of J2SDK to
develop Java applications that can communicate with databases.
The following figure shows the Airline Reservation System developed in
Java interacting with the Airlines database using the JDBC API.
JDBC Architecture
Q5M2 – 3SC Dudy Fathan Ali S.Kom
JDBC architecture provides the mechanism to translate Java
statements into SQL statements.
It can be classified into two layers:
JDBC application layer
JDBC driver layer
JDBC Drivers
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Convert SQL statements into a form that a particular database can interpret.
Retrieve the result of SQL statements and convert the result into equivalent
JDBC API class objects.
Are of four types:
JDBC-ODBC Bridge driver
Native-API Partly-Java driver
JDBC-Net Pure-Java driver
Native Protocol Pure-Java driver
Using JDBC API
Q5M2 – 3SC Dudy Fathan Ali S.Kom
The JDBC API classes and interfaces are available in the java.sql and
the javax.sql packages.
The commonly used classes and interfaces in the JDBC API are:
DriverManager class: Loads the driver for a database.
Driver interface: Represents a database driver. All JDBC driver classes
must implement the Driver interface.
Connection interface: Enables you to establish a connection between a
Java application and a database.
Statement interface: Enables you to execute SQL statements.
ResultSet interface: Represents the information retrieved from a
database.
SQLException class: Provides information about the exceptions that
occur while interacting with databases.
Using JDBC API (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Steps to create a JDBC application are:
Load a driver
Connect to a database
Create and execute JDBC statements
Handle SQL exceptions
Loading a Driver
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Driver can be loaded:
Programmatically:
Using the forName() method
Using the registerDriver()method
Manually:
By setting system property
Loading a Driver
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Driver can be loaded:
Programmatically:
Using the forName() method
Using the registerDriver()method
Manually:
By setting system property
Using the forName() Method:
The forName() method is available in the
java.lang.Class class.
The forName() method loads the JDBC driver and registers
the driver with the driver manager.
The method call to use the the forName() method is:
Class.forName("com.microsoft.sqlserver.jdbc.S
QLServerDriver");
Loading a Driver (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Using the registerDriver() Method:
You can create an instance of the Driver class to load a JDBC driver.
This instance enables you to provide the name of the driver class at run
time.
The statement to create an instance of the Driver class is:
Driver d = new
com.microsoft.sqlserver.jdbc.SQLServerDriver();
You need to call the registerDriver() method to register the Driver
object with the DriverManager.
The method call to register the Type 4 driver is:
DriverManager.registerDriver(d);
Loading a Driver (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Setting the System Property:
Add the driver name to the jdbc.drivers system property to load a
JDBC driver.
Use the –D command line option to set the system property on the
command line.
The command to set the system property is:
java –Djdbc.drivers=
com.microsoft.sqlserver.jdbc.SQLServerDriver
SampleApplication
Connecting to a Database
Q5M2 – 3SC Dudy Fathan Ali S.Kom
The DriverManager class provides the getConnection() method to
create a Connection object.
The getConnection() method method has the following three forms:
Connection getConnection (String <url>)
Connection getConnection (String <url>, String
<username>, String <password>)
Connection getConnection (String <url>, Properties
<properties>)
Creating and Executing JDBC Statements
Q5M2 – 3SC Dudy Fathan Ali S.Kom
JDBC Statements can be created and executed as follows:
The Connection object provides the createStatement() method to create
a Statement object.
You can use static SQL statements to send requests to a database to retrieve
results.
The Statement interface contains the following methods to send static SQL
statements to a database:
ResultSet executeQuery(String str)
int executeUpdate(String str)
boolean execute(String str)
Creating and Executing JDBC Statements (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Various database operations that you can perform using a
Java application are:
Querying a table
Inserting rows in a table
Updating rows in a table
Deleting rows from a table
Creating a table
Altering and dropping a table
Creating and Executing JDBC Statements (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Querying a table:
The SELECT statement is executed using the executeQuery()
method and returns the output in the form of a ResultSet object.
The code snippet to retrieve data from the Authors table is:
String str = "SELECT * FROM Authors";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(str);
Creating and Executing JDBC Statements (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Inserting rows in a table:
The executeUpdate() method enables you to add rows in a table.
The code snippet to insert a row in the Authors table is:
String str = " INSERT INTO Authors (au_id, au_name,
phone, address, city, state, zip) VALUES
(‘a004’, ‘Ringer Albert’, ‘8018260752’, ‘ 67
Seventh Av.’, ‘Salt Lake City’, ‘UT’, ’100000078’)";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
Creating and Executing JDBC Statements (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Updating and Deleting rows in a table:
The code snippet to modify a row from the Authors table is:
String str = "UPDATE Authors SET address='10932
Second Av.’ WHERE au_id=‘a001’";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
The code snippet to delete a row from the Authors table is:
String str = "DELETE FROM Authors WHERE
au_id=‘a005’";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
Creating and Executing JDBC Statements (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Creating a table:
The CREATE TABLE statement is used to create and define the
structure of a table in a database.
The code snippet to create a table is:
String str="CREATE TABLE Publishers"
+"(pub_id VARCHAR(5),"
+"pub_name VARCHAR(50),"
+"phone INTEGER,"
+"address VARCHAR(50), "
+"city VARCHAR(50), "
+"ZIP VARCHAR(20))";
Statement stmt=con.createStatement();
stmt.execute(str);
Creating and Executing JDBC Statements (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Altering and Dropping a table:
DDL provides the ALTER statement to modify the definition of
database object.
The code snippet to add a column to the Books table is:
String str="ALTER TABLE Books “+"ADD price
INTEGER";
Statement stmt=con.createStatement();
stmt.execute(str);
DDL provides the DROP TABLE statement to drop a table from a
database.
The code snippet to drop the Books table from a database is:
String str="DROP TABLE Books";
Statement stmt=con.createStatement();
stmt.execute(str);
Handling SQL Exceptions
Q5M2 – 3SC Dudy Fathan Ali S.Kom
SQL Exceptions can be handled as follows:
The java.sql package provides the SQLException class, which is
derived from the java.lang.Exception class.
You can catch the SQLException in a Java application using the try and
catch exception handling block.
The SQLException class contains various methods that provide error
information, these methods are:
int getErrorCode(): Returns the error code associated with the error
occurred.
String getSQLState(): Returns X/Open error code.
SQLException getNextException(): Returns the next exception in the
chain of exceptions.
Result Set
Q5M2 – 3SC Dudy Fathan Ali S.Kom
A ResultSet object maintains a cursor that enables you to move
through the rows stored in a ResultSet object.
The various types of ResultSet objects to store the output
returned by a database are:
Read only: Allows you to only read the rows in a ResultSet object.
Forward only: Moves the result set cursor from first row to last row in
forward direction only.
Scrollable: Moves the result set cursor forward or backward through
the result set.
Updatable: Allows you to update the result set rows retrieved from a
database table.
Types of Result Set
Q5M2 – 3SC Dudy Fathan Ali S.Kom
The following table lists various fields of ResultSet interface
that you can use to specify the type of a ResultSet object.
ResultSet Fields Description
TYPE_SCROLL_SENTIT
IVE
Specifies that the cursor of the ResultSet object is
scrollable and it reflects the changes in the data made
by other users.
TYPE_SCROLL_INSENS
ITIVE
Specifies that the cursor of the ResultSet object is
scrollable and it does not reflect changes in the data
made by other users.
TYPE_FORWARD_ONLY Specifies that the cursor of the ResultSet object
moves in forward direction only from the first row to
the last row.
Types of Result Set (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
The following table lists various fields of the ResultSet
interface that you can use to specify different concurrency modes
of result sets.
ResultSet Fields Description
CONCUR_READ_ONLY Specifies the concurrency mode that
does not allow you to update the
ResultSet object.
CONCUR_UPDATABLE Specifies the concurrency mode that
allows you to update the ResultSet
object.
Types of Result Set (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
The createStatement() method has the following three overloaded
forms:
Statement createStatement()
Statement createStatement(int, int)
Statement createStatement(int, int, int)
Methods of Result Set Interface
Q5M2 – 3SC Dudy Fathan Ali S.Kom
The following tables lists some of the methods of ResultSet
interface:
Method Description
boolean first() Shifts the control of a result set cursor to the
first row of the result set.
boolean isFirst() Determines whether the result set cursor
points to the first row of the result set.
boolean last() Shifts the control of a result set cursor to the
last row of the result set.
boolean isLast() Determines whether the result set cursor
points to the last row of the result set.
Methods of Result Set Interface (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
JDBC allows you to create an updatable result set that enables you to modify
the rows in the result set.
The following table lists some of the methods used with updatable result
set:
Method Description
void insertRow() Inserts a row in the current ResultSet object and
the underlying database table.
void deleteRow() Deletes a row from the current ResultSet object
and the underlying database table.
Summary
Q5M2 – 3SC Dudy Fathan Ali S.Kom
In this session, you learned that:
JDBC Architecture consists of two layers:
JDBC application layer: Signifies a Java application that uses the JDBC API to
interact with the JDBC driver manager.
JDBC driver layer: Contains a driver, such as an SQL Server driver, which
enables a Java application to connect to a database. This layer acts as an
interface between a Java application and a database.
The JDBC driver manager manages various JDBC drivers.
The JDBC driver is software that a Java application uses to access a
database.
JDBC supports four types of drivers:
JDBC-ODBC Bridge driver
Native-API Partly-Java driver
JDBC-Net Pure-Java driver
Native Protocol Pure-Java driver
Summary (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
The JDBC API consists of various classes and interfaces that enable
Java applications to interact with databases.
The classes and interfaces of the JDBC API are defined in the java.sql
and javax.sql packages.
You can load a driver and register it with the driver manager either
programmatically or manually.
Two ways to load and register a driver programmatically are:
Using the Class.forName() method
Using the registerDriver() method
You can add the driver name to the jdbc.drivers system property to load
and register a JDBC driver manually.
A Connection object establishes a connection between a Java
application and a database.
A Statement object sends requests to and retrieves results from a
database.
Summary (contd.)
Q5M2 – 3SC Dudy Fathan Ali S.Kom
You can insert, update, and delete data from a table using the DML
statements in Java applications.
You can create, alter, and drop tables from a database using the DDL
statements in Java applications.
A ResultSet object stores the result retrieved from a database when a
SELECT statement is executed.
You can create various types of ResultSet objects such as read only,
updatable, and forward only.
Q5M2 – 3SC Dudy Fathan Ali S.Kom
Thank You!
Dudy Fathan Ali S.Kom
dudy.fathan@eng.ui.ac.id
Source : NIIT Courseware Q5M2 ADO.NET & JDBC

Mais conteúdo relacionado

Mais procurados

Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsRichie Rump
 
The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181Mahmoud Samir Fayed
 
Teradata client4
Teradata client4Teradata client4
Teradata client4Madhu Bandi
 
Advanced SQL - Database Access from Programming Languages
Advanced SQL - Database Access  from Programming LanguagesAdvanced SQL - Database Access  from Programming Languages
Advanced SQL - Database Access from Programming LanguagesS.Shayan Daneshvar
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.netNgeam Soly
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow BasicsPramod Singla
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaPawanMM
 
05 entity framework
05 entity framework05 entity framework
05 entity frameworkglubox
 
Database Programming
Database ProgrammingDatabase Programming
Database ProgrammingHenry Osborne
 

Mais procurados (20)

Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
PostgreSQL - Case Study
PostgreSQL - Case StudyPostgreSQL - Case Study
PostgreSQL - Case Study
 
Sql server
Sql serverSql server
Sql server
 
Database programming
Database programmingDatabase programming
Database programming
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181
 
Teradata client4
Teradata client4Teradata client4
Teradata client4
 
Advanced SQL - Database Access from Programming Languages
Advanced SQL - Database Access  from Programming LanguagesAdvanced SQL - Database Access  from Programming Languages
Advanced SQL - Database Access from Programming Languages
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics
 
Ado.net
Ado.netAdo.net
Ado.net
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 

Destaque

Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servletsNuha Noor
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Data Access Layer как страховка на случай миграции СУБД
Data Access Layer как страховка на случай миграции СУБДData Access Layer как страховка на случай миграции СУБД
Data Access Layer как страховка на случай миграции СУБДCUSTIS
 
Work with my_sql_-_database_in_java
Work with my_sql_-_database_in_javaWork with my_sql_-_database_in_java
Work with my_sql_-_database_in_javaAsya Dudnik
 
Lecture data base programming part2
Lecture data base programming part2Lecture data base programming part2
Lecture data base programming part2ganzorigb
 
Lecture data base programming part1
Lecture data base programming part1Lecture data base programming part1
Lecture data base programming part1ganzorigb
 
Коллекции в Java
Коллекции в JavaКоллекции в Java
Коллекции в Javametaform
 
Работа с БД в Java
Работа с БД в JavaРабота с БД в Java
Работа с БД в Javametaform
 
Lecture data base programming part3
Lecture data base programming part3Lecture data base programming part3
Lecture data base programming part3ganzorigb
 
PostgreSQL и JDBC: выжимаем все соки
PostgreSQL и JDBC: выжимаем все сокиPostgreSQL и JDBC: выжимаем все соки
PostgreSQL и JDBC: выжимаем все сокиVladimir Sitnikov
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Kochi city study(intro, history, demography, infrastructure, economy, tourism)
Kochi  city study(intro, history, demography, infrastructure, economy, tourism)Kochi  city study(intro, history, demography, infrastructure, economy, tourism)
Kochi city study(intro, history, demography, infrastructure, economy, tourism)Arun Chandra Babu
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Som Prakash Rai
 
Jdbc Dao it-slideshares.blogspot.com
Jdbc Dao it-slideshares.blogspot.comJdbc Dao it-slideshares.blogspot.com
Jdbc Dao it-slideshares.blogspot.comphanleson
 

Destaque (20)

Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Data Access Layer как страховка на случай миграции СУБД
Data Access Layer как страховка на случай миграции СУБДData Access Layer как страховка на случай миграции СУБД
Data Access Layer как страховка на случай миграции СУБД
 
Work with my_sql_-_database_in_java
Work with my_sql_-_database_in_javaWork with my_sql_-_database_in_java
Work with my_sql_-_database_in_java
 
Lecture data base programming part2
Lecture data base programming part2Lecture data base programming part2
Lecture data base programming part2
 
Lecture data base programming part1
Lecture data base programming part1Lecture data base programming part1
Lecture data base programming part1
 
Коллекции в Java
Коллекции в JavaКоллекции в Java
Коллекции в Java
 
Работа с БД в Java
Работа с БД в JavaРабота с БД в Java
Работа с БД в Java
 
Lecture data base programming part3
Lecture data base programming part3Lecture data base programming part3
Lecture data base programming part3
 
PostgreSQL и JDBC: выжимаем все соки
PostgreSQL и JDBC: выжимаем все сокиPostgreSQL и JDBC: выжимаем все соки
PostgreSQL и JDBC: выжимаем все соки
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Kochi city study(intro, history, demography, infrastructure, economy, tourism)
Kochi  city study(intro, history, demography, infrastructure, economy, tourism)Kochi  city study(intro, history, demography, infrastructure, economy, tourism)
Kochi city study(intro, history, demography, infrastructure, economy, tourism)
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
 
Jdbc Dao it-slideshares.blogspot.com
Jdbc Dao it-slideshares.blogspot.comJdbc Dao it-slideshares.blogspot.com
Jdbc Dao it-slideshares.blogspot.com
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 

Semelhante a Database Connectivity with JDBC

Semelhante a Database Connectivity with JDBC (20)

Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Database connect
Database connectDatabase connect
Database connect
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 

Mais de Dudy Ali

Understanding COM+
Understanding COM+Understanding COM+
Understanding COM+Dudy Ali
 
Distributed Application Development (Introduction)
Distributed Application Development (Introduction)Distributed Application Development (Introduction)
Distributed Application Development (Introduction)Dudy Ali
 
Network Socket Programming with JAVA
Network Socket Programming with JAVANetwork Socket Programming with JAVA
Network Socket Programming with JAVADudy Ali
 
Review Materi ASP.NET
Review Materi ASP.NETReview Materi ASP.NET
Review Materi ASP.NETDudy Ali
 
XML Schema Part 2
XML Schema Part 2XML Schema Part 2
XML Schema Part 2Dudy Ali
 
XML Schema Part 1
XML Schema Part 1XML Schema Part 1
XML Schema Part 1Dudy Ali
 
Rendering XML Document
Rendering XML DocumentRendering XML Document
Rendering XML DocumentDudy Ali
 
Pengantar XML
Pengantar XMLPengantar XML
Pengantar XMLDudy Ali
 
Pengantar XML DOM
Pengantar XML DOMPengantar XML DOM
Pengantar XML DOMDudy Ali
 
Pengantar ADO.NET
Pengantar ADO.NETPengantar ADO.NET
Pengantar ADO.NETDudy Ali
 
XML - Displaying Data ith XSLT
XML - Displaying Data ith XSLTXML - Displaying Data ith XSLT
XML - Displaying Data ith XSLTDudy Ali
 
Algorithm & Data Structure - Algoritma Pengurutan
Algorithm & Data Structure - Algoritma PengurutanAlgorithm & Data Structure - Algoritma Pengurutan
Algorithm & Data Structure - Algoritma PengurutanDudy Ali
 
Algorithm & Data Structure - Pengantar
Algorithm & Data Structure - PengantarAlgorithm & Data Structure - Pengantar
Algorithm & Data Structure - PengantarDudy Ali
 
Object Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesObject Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesDudy Ali
 
Object Oriented Programming - Inheritance
Object Oriented Programming - InheritanceObject Oriented Programming - Inheritance
Object Oriented Programming - InheritanceDudy Ali
 
Object Oriented Programming - File Input & Output
Object Oriented Programming - File Input & OutputObject Oriented Programming - File Input & Output
Object Oriented Programming - File Input & OutputDudy Ali
 
Object Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & DestructorsObject Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & DestructorsDudy Ali
 
Object Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationObject Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationDudy Ali
 
Web Programming Syaria - Pengenalan Halaman Web
Web Programming Syaria - Pengenalan Halaman WebWeb Programming Syaria - Pengenalan Halaman Web
Web Programming Syaria - Pengenalan Halaman WebDudy Ali
 
Web Programming Syaria - PHP
Web Programming Syaria - PHPWeb Programming Syaria - PHP
Web Programming Syaria - PHPDudy Ali
 

Mais de Dudy Ali (20)

Understanding COM+
Understanding COM+Understanding COM+
Understanding COM+
 
Distributed Application Development (Introduction)
Distributed Application Development (Introduction)Distributed Application Development (Introduction)
Distributed Application Development (Introduction)
 
Network Socket Programming with JAVA
Network Socket Programming with JAVANetwork Socket Programming with JAVA
Network Socket Programming with JAVA
 
Review Materi ASP.NET
Review Materi ASP.NETReview Materi ASP.NET
Review Materi ASP.NET
 
XML Schema Part 2
XML Schema Part 2XML Schema Part 2
XML Schema Part 2
 
XML Schema Part 1
XML Schema Part 1XML Schema Part 1
XML Schema Part 1
 
Rendering XML Document
Rendering XML DocumentRendering XML Document
Rendering XML Document
 
Pengantar XML
Pengantar XMLPengantar XML
Pengantar XML
 
Pengantar XML DOM
Pengantar XML DOMPengantar XML DOM
Pengantar XML DOM
 
Pengantar ADO.NET
Pengantar ADO.NETPengantar ADO.NET
Pengantar ADO.NET
 
XML - Displaying Data ith XSLT
XML - Displaying Data ith XSLTXML - Displaying Data ith XSLT
XML - Displaying Data ith XSLT
 
Algorithm & Data Structure - Algoritma Pengurutan
Algorithm & Data Structure - Algoritma PengurutanAlgorithm & Data Structure - Algoritma Pengurutan
Algorithm & Data Structure - Algoritma Pengurutan
 
Algorithm & Data Structure - Pengantar
Algorithm & Data Structure - PengantarAlgorithm & Data Structure - Pengantar
Algorithm & Data Structure - Pengantar
 
Object Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesObject Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference Types
 
Object Oriented Programming - Inheritance
Object Oriented Programming - InheritanceObject Oriented Programming - Inheritance
Object Oriented Programming - Inheritance
 
Object Oriented Programming - File Input & Output
Object Oriented Programming - File Input & OutputObject Oriented Programming - File Input & Output
Object Oriented Programming - File Input & Output
 
Object Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & DestructorsObject Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & Destructors
 
Object Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationObject Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & Encapsulation
 
Web Programming Syaria - Pengenalan Halaman Web
Web Programming Syaria - Pengenalan Halaman WebWeb Programming Syaria - Pengenalan Halaman Web
Web Programming Syaria - Pengenalan Halaman Web
 
Web Programming Syaria - PHP
Web Programming Syaria - PHPWeb Programming Syaria - PHP
Web Programming Syaria - PHP
 

Último

Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 

Último (20)

Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 

Database Connectivity with JDBC

  • 1. Q5M2 – 3SC Dudy Fathan Ali S.Kom JDBC Q5M2 – 3SC Dudy Fathan Ali, S.Kom (DFA) 2015 CEP - CCIT Fakultas Teknik Universitas Indonesia
  • 2. Objectives Q5M2 – 3SC Dudy Fathan Ali S.Kom In this session, you will learn to: Identify the layers in JDBC architecture Identify the types of JDBC drivers Use the classes and interfaces of JDBC application programming interface Understand and execute the steps to create JDBC applications
  • 3. Database Connectivity Q5M2 – 3SC Dudy Fathan Ali S.Kom Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases. The following figure shows the Airline Reservation System developed in Java interacting with the Airlines database using the JDBC API.
  • 4. JDBC Architecture Q5M2 – 3SC Dudy Fathan Ali S.Kom JDBC architecture provides the mechanism to translate Java statements into SQL statements. It can be classified into two layers: JDBC application layer JDBC driver layer
  • 5. JDBC Drivers Q5M2 – 3SC Dudy Fathan Ali S.Kom Convert SQL statements into a form that a particular database can interpret. Retrieve the result of SQL statements and convert the result into equivalent JDBC API class objects. Are of four types: JDBC-ODBC Bridge driver Native-API Partly-Java driver JDBC-Net Pure-Java driver Native Protocol Pure-Java driver
  • 6. Using JDBC API Q5M2 – 3SC Dudy Fathan Ali S.Kom The JDBC API classes and interfaces are available in the java.sql and the javax.sql packages. The commonly used classes and interfaces in the JDBC API are: DriverManager class: Loads the driver for a database. Driver interface: Represents a database driver. All JDBC driver classes must implement the Driver interface. Connection interface: Enables you to establish a connection between a Java application and a database. Statement interface: Enables you to execute SQL statements. ResultSet interface: Represents the information retrieved from a database. SQLException class: Provides information about the exceptions that occur while interacting with databases.
  • 7. Using JDBC API (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Steps to create a JDBC application are: Load a driver Connect to a database Create and execute JDBC statements Handle SQL exceptions
  • 8. Loading a Driver Q5M2 – 3SC Dudy Fathan Ali S.Kom Driver can be loaded: Programmatically: Using the forName() method Using the registerDriver()method Manually: By setting system property
  • 9. Loading a Driver Q5M2 – 3SC Dudy Fathan Ali S.Kom Driver can be loaded: Programmatically: Using the forName() method Using the registerDriver()method Manually: By setting system property Using the forName() Method: The forName() method is available in the java.lang.Class class. The forName() method loads the JDBC driver and registers the driver with the driver manager. The method call to use the the forName() method is: Class.forName("com.microsoft.sqlserver.jdbc.S QLServerDriver");
  • 10. Loading a Driver (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Using the registerDriver() Method: You can create an instance of the Driver class to load a JDBC driver. This instance enables you to provide the name of the driver class at run time. The statement to create an instance of the Driver class is: Driver d = new com.microsoft.sqlserver.jdbc.SQLServerDriver(); You need to call the registerDriver() method to register the Driver object with the DriverManager. The method call to register the Type 4 driver is: DriverManager.registerDriver(d);
  • 11. Loading a Driver (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Setting the System Property: Add the driver name to the jdbc.drivers system property to load a JDBC driver. Use the –D command line option to set the system property on the command line. The command to set the system property is: java –Djdbc.drivers= com.microsoft.sqlserver.jdbc.SQLServerDriver SampleApplication
  • 12. Connecting to a Database Q5M2 – 3SC Dudy Fathan Ali S.Kom The DriverManager class provides the getConnection() method to create a Connection object. The getConnection() method method has the following three forms: Connection getConnection (String <url>) Connection getConnection (String <url>, String <username>, String <password>) Connection getConnection (String <url>, Properties <properties>)
  • 13. Creating and Executing JDBC Statements Q5M2 – 3SC Dudy Fathan Ali S.Kom JDBC Statements can be created and executed as follows: The Connection object provides the createStatement() method to create a Statement object. You can use static SQL statements to send requests to a database to retrieve results. The Statement interface contains the following methods to send static SQL statements to a database: ResultSet executeQuery(String str) int executeUpdate(String str) boolean execute(String str)
  • 14. Creating and Executing JDBC Statements (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Various database operations that you can perform using a Java application are: Querying a table Inserting rows in a table Updating rows in a table Deleting rows from a table Creating a table Altering and dropping a table
  • 15. Creating and Executing JDBC Statements (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Querying a table: The SELECT statement is executed using the executeQuery() method and returns the output in the form of a ResultSet object. The code snippet to retrieve data from the Authors table is: String str = "SELECT * FROM Authors"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(str);
  • 16. Creating and Executing JDBC Statements (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Inserting rows in a table: The executeUpdate() method enables you to add rows in a table. The code snippet to insert a row in the Authors table is: String str = " INSERT INTO Authors (au_id, au_name, phone, address, city, state, zip) VALUES (‘a004’, ‘Ringer Albert’, ‘8018260752’, ‘ 67 Seventh Av.’, ‘Salt Lake City’, ‘UT’, ’100000078’)"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str);
  • 17. Creating and Executing JDBC Statements (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Updating and Deleting rows in a table: The code snippet to modify a row from the Authors table is: String str = "UPDATE Authors SET address='10932 Second Av.’ WHERE au_id=‘a001’"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); The code snippet to delete a row from the Authors table is: String str = "DELETE FROM Authors WHERE au_id=‘a005’"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str);
  • 18. Creating and Executing JDBC Statements (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Creating a table: The CREATE TABLE statement is used to create and define the structure of a table in a database. The code snippet to create a table is: String str="CREATE TABLE Publishers" +"(pub_id VARCHAR(5)," +"pub_name VARCHAR(50)," +"phone INTEGER," +"address VARCHAR(50), " +"city VARCHAR(50), " +"ZIP VARCHAR(20))"; Statement stmt=con.createStatement(); stmt.execute(str);
  • 19. Creating and Executing JDBC Statements (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom Altering and Dropping a table: DDL provides the ALTER statement to modify the definition of database object. The code snippet to add a column to the Books table is: String str="ALTER TABLE Books “+"ADD price INTEGER"; Statement stmt=con.createStatement(); stmt.execute(str); DDL provides the DROP TABLE statement to drop a table from a database. The code snippet to drop the Books table from a database is: String str="DROP TABLE Books"; Statement stmt=con.createStatement(); stmt.execute(str);
  • 20. Handling SQL Exceptions Q5M2 – 3SC Dudy Fathan Ali S.Kom SQL Exceptions can be handled as follows: The java.sql package provides the SQLException class, which is derived from the java.lang.Exception class. You can catch the SQLException in a Java application using the try and catch exception handling block. The SQLException class contains various methods that provide error information, these methods are: int getErrorCode(): Returns the error code associated with the error occurred. String getSQLState(): Returns X/Open error code. SQLException getNextException(): Returns the next exception in the chain of exceptions.
  • 21. Result Set Q5M2 – 3SC Dudy Fathan Ali S.Kom A ResultSet object maintains a cursor that enables you to move through the rows stored in a ResultSet object. The various types of ResultSet objects to store the output returned by a database are: Read only: Allows you to only read the rows in a ResultSet object. Forward only: Moves the result set cursor from first row to last row in forward direction only. Scrollable: Moves the result set cursor forward or backward through the result set. Updatable: Allows you to update the result set rows retrieved from a database table.
  • 22. Types of Result Set Q5M2 – 3SC Dudy Fathan Ali S.Kom The following table lists various fields of ResultSet interface that you can use to specify the type of a ResultSet object. ResultSet Fields Description TYPE_SCROLL_SENTIT IVE Specifies that the cursor of the ResultSet object is scrollable and it reflects the changes in the data made by other users. TYPE_SCROLL_INSENS ITIVE Specifies that the cursor of the ResultSet object is scrollable and it does not reflect changes in the data made by other users. TYPE_FORWARD_ONLY Specifies that the cursor of the ResultSet object moves in forward direction only from the first row to the last row.
  • 23. Types of Result Set (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom The following table lists various fields of the ResultSet interface that you can use to specify different concurrency modes of result sets. ResultSet Fields Description CONCUR_READ_ONLY Specifies the concurrency mode that does not allow you to update the ResultSet object. CONCUR_UPDATABLE Specifies the concurrency mode that allows you to update the ResultSet object.
  • 24. Types of Result Set (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom The createStatement() method has the following three overloaded forms: Statement createStatement() Statement createStatement(int, int) Statement createStatement(int, int, int)
  • 25. Methods of Result Set Interface Q5M2 – 3SC Dudy Fathan Ali S.Kom The following tables lists some of the methods of ResultSet interface: Method Description boolean first() Shifts the control of a result set cursor to the first row of the result set. boolean isFirst() Determines whether the result set cursor points to the first row of the result set. boolean last() Shifts the control of a result set cursor to the last row of the result set. boolean isLast() Determines whether the result set cursor points to the last row of the result set.
  • 26. Methods of Result Set Interface (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom JDBC allows you to create an updatable result set that enables you to modify the rows in the result set. The following table lists some of the methods used with updatable result set: Method Description void insertRow() Inserts a row in the current ResultSet object and the underlying database table. void deleteRow() Deletes a row from the current ResultSet object and the underlying database table.
  • 27. Summary Q5M2 – 3SC Dudy Fathan Ali S.Kom In this session, you learned that: JDBC Architecture consists of two layers: JDBC application layer: Signifies a Java application that uses the JDBC API to interact with the JDBC driver manager. JDBC driver layer: Contains a driver, such as an SQL Server driver, which enables a Java application to connect to a database. This layer acts as an interface between a Java application and a database. The JDBC driver manager manages various JDBC drivers. The JDBC driver is software that a Java application uses to access a database. JDBC supports four types of drivers: JDBC-ODBC Bridge driver Native-API Partly-Java driver JDBC-Net Pure-Java driver Native Protocol Pure-Java driver
  • 28. Summary (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom The JDBC API consists of various classes and interfaces that enable Java applications to interact with databases. The classes and interfaces of the JDBC API are defined in the java.sql and javax.sql packages. You can load a driver and register it with the driver manager either programmatically or manually. Two ways to load and register a driver programmatically are: Using the Class.forName() method Using the registerDriver() method You can add the driver name to the jdbc.drivers system property to load and register a JDBC driver manually. A Connection object establishes a connection between a Java application and a database. A Statement object sends requests to and retrieves results from a database.
  • 29. Summary (contd.) Q5M2 – 3SC Dudy Fathan Ali S.Kom You can insert, update, and delete data from a table using the DML statements in Java applications. You can create, alter, and drop tables from a database using the DDL statements in Java applications. A ResultSet object stores the result retrieved from a database when a SELECT statement is executed. You can create various types of ResultSet objects such as read only, updatable, and forward only.
  • 30. Q5M2 – 3SC Dudy Fathan Ali S.Kom Thank You! Dudy Fathan Ali S.Kom dudy.fathan@eng.ui.ac.id Source : NIIT Courseware Q5M2 ADO.NET & JDBC