0% found this document useful (0 votes)
2 views79 pages

Chapter 3 - Database Connectivity

Chapter 3 covers database connectivity using JDBC, detailing how Java applications can connect to relational databases, execute SQL queries, and handle results. It explains the types of JDBC drivers, their functionalities, and the steps required to establish a connection, including loading the driver and defining the connection URL. The chapter also provides an overview of SQL commands and database management systems, emphasizing the importance of JDBC in Java programming for database interactions.

Uploaded by

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

Chapter 3 - Database Connectivity

Chapter 3 covers database connectivity using JDBC, detailing how Java applications can connect to relational databases, execute SQL queries, and handle results. It explains the types of JDBC drivers, their functionalities, and the steps required to establish a connection, including loading the driver and defining the connection URL. The chapter also provides an overview of SQL commands and database management systems, emphasizing the importance of JDBC in Java programming for database interactions.

Uploaded by

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

Chapter 3: Database

Connectivity
Pre-Knowledge 2

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Database

 Table

 Manipulating Table
 Insert

 Update

 Select

 Delete

 Using Joins

 Stored Procedures
Objectives 3

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 By the end of this chapter, you should be able to:
 be aware of what JDBC is and why it is needed;

 Know the four types of JDBC driver;

 know how to use JDBC to make a connection to a database;

 know how to use JDBC to execute SQL queries and how to handle the
results returned;
Overview 4
 A database is a means of storing information in such a way

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
that information can be retrieved from it.

 Relational database: presents information in tables with


rows and columns.

 Table: a collection of objects of the same type (rows).

 Data in a table can be related according to common keys.


 Programs written in Java are able to communicate with relational

databases (whether local or remote) via the Java Database


Connectivity (JDBC) API
Database Management 5

System
One of the major problems with databases has been the feature wars

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
between the database companies.

 There is a “standard” database language, Structured Query Language


(SQL-92), but you must usually know which database vendor you’re
working with despite the standard.

 Popular database management systems


Overview of SQL 6

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 The standard means of accessing a relational database is to use SQL
(Structured Query Language).

 SQL is Standard language for querying and manipulating data

 SLQ uses certain commands like:


 Data Definition Language (DDL)
 Used for defining the DB schema (create and modify the structure of database

objects in the database)


 Create/alter/drop/truncate/rename/comment tables and their attributes

 Data Manipulation Language (DML)


 Query one or more tables


Overview of SQL 7

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
PName Price Category Manufacturer
Product
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi

SELECT
SELECT **
FROM
FROM Product
Product “selection”
WHERE
WHERE category=‘Gadgets’
category=‘Gadgets’

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks


Powergizmo $29.99 Gadgets GizmoWorks
Overview of SQL: Select Query 8

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
SELECT

[DISTINCT | ALL] <column-list>

FROM <table-names>

[WHERE <condition>]

[ORDER BY <column-list>]

[GROUP BY <column-list>]

[HAVING <condition>]

([]-
optional, | - or)
Advanced Programming Chapter Three:
Database Connectivity
9

Thursday, March 13, 2025


Connecting Java Application
to Database Server
JDBC 10
 JDBC helps to write Java applications that manage these three

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
programming activities:
1. Connect to a database
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in
answer to your query
 Ultimate goal of JDBC
 Programmers can write applications in the Java to access any database,
using standard SQL statements or even specialized extensions of SQL
while following Java language conventions.
 Database vendors and database tool vendors can supply the low-level
drivers. Thus, they can optimize their drivers for their specific products.
 The JDBC classes and interfaces are in the java.sql package.
JDBC Architectural 11
 Components
Client Application

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 the application that is accessing the DB
 Driver
 the “bridge” between the client and the DB
 vendor-specific
 sends the client requests to the server (after possibly some
processing) and presents the results to the client
 Driver Manager
 manages the different drivers that can co-exist in the same client
 Database Server
 the DB engine that supports the application
 located most likely on a different machine than the client
JDBC Basic Steps 12

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Using JDBC to access a database requires several steps, as
described below by importing (import java.sql.*;)

1. Loading the appropriate JDBC Driver

2. Establish a connection using driver

3. Use the connection to create Statement

4. Executing Statement

5. Processing Result

6. Closing Connection
Step 1: Loading JDBC
Driver
IN ORDER TO USE JDBC FOR THE ACCESSING OF DATA FROM A PARTICULAR TYPE OF
RELATIONAL DATABASE, IT IS NECESSARY TO PROVIDE SOME MEDIATING SOFTWARE THAT
WILL ALLOW JDBC TO COMMUNICATE WITH THE VENDOR-SPECIFIC API FOR THAT DATABASE.
SUCH SOFTWARE IS REFERRED TO AS A DRIVER.
A JDBC Driver 14
 Suitable drivers are usually supplied either by the database

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
vendors themselves or by third parties.
 Is an interpreter that translates JDBC method calls to vendor-
specific database commands

JDBC calls Database


Driver Database
commands

 Can also provide a vendor’s extensions to the JDBC standard


 JDBC driver implementations vary because of the wide variety
of operating systems and hardware platforms in which Java
operates.
JDBC Driver Types 15

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 The JDBC specification classifies drivers
into four categories:
 Types 1 and 2:
 Rely heavily on additional software (typically C/C++
DLLs) installed on the client computer to provide
database connectivity.
 Java and JDBC use these components to interact with
the database.

 Types 3 and 4:
 Pure Java implementations and require no additional
software to be installed on the client, except for the
JDBC driver.
 Fortunately, packaging the JDBC driver with your
software distribution is trivial.
Type 1: JDBC−ODBC bridges 16

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Before Java came onto the scene, Microsoft had introduced its own
solution to the problem of accessing databases that have different
internal formats: Open Database Connectivity (ODBC).
 Sun provides the JDBC-ODBC bridge driver in package
sun.jdbc.odbc
 This driver converts the JDBC protocol into the corresponding
ODBC and allows Java programmers to access databases for which
there are ODBC drivers.
 “…the bridge driver included in the SDK is appropriate only for
experimental use or when no other driver is available”.
Type 1: JDBC−ODBC bridges 17

 Thus, this category works with ODBC drivers supplied by

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
your database vendor or a third party.
 To use the bridge, you must first have an ODBC driver
specifically for your database and any additional software
that you need for connectivity.
 Consists of a Java part that translates the JDBC interface
calls to ODBC calls. ODBC bridge then calls the ODBC driver
of the given database.
Type 1: JDBC−ODBC bridges 18

 Pros

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Cons
 Can access local  You must set up and maintain
databases such as ODBC data sources.
Microsoft Access and  Slow. The extra ODBC layer
FoxPro.
necessitates additional
 No enterprise−level
processing.
database required.
 May require additional client
 Useful for testing basic
software such as database
JDBC features on stand
network connectivity components.
alone Windows
computers.  Not usable when deployment
requires automatic downloading
and configuration of applications.
Type 2: JDBC−native API,
19
partially java
 JDBC API calls are converted into native C/C++ API

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
calls, which are unique to the database.
 The vendor-specific driver must be installed on
each client machine.
 Oracle Call Interface (OCI) driver is example
Type 2: Native API 20

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
Pros
 Faster than Type 1 because the ODBC layer is removed.

 Native code optimized for your platform and DBMS

Cons
 A vendor−specific API must be installed on client computer.

 Not usable when deployment requires automatic


downloading and configuration of applications.
Type 3: JDBC−network 21

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 The JDBC clients use standard network sockets to
communicate with a middleware application server.
 The socket information is then translated by the
middleware application server into the call format
required by the DBMS, and forwarded to the database
server.
Type 3: JDBC−Network 22

Application server makes calls for the client

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
application(JDBC driver), then using vendor
specific driver application communicates to DB.
Application server might use a Type 1, 2, or 4
driver to communicate with the database
Pros
 No additional client software required.
 Application server may give you access to multiple
DBMSs.
Cons
 Middleware product or application server required.
 May require additional configuration for Internet use.
Type 4: 100% Java 23

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
This driver is implemented entirely in Java and encapsulates the
database−specific network protocols to communicate directly with the
DBMS.

A pure Java-based driver communicates directly with the vendor's


database through socket connection.

The highest performance driver available for the database and is usually
provided by the vendor itself.
Type 4: 100% Java 24

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
Extremely flexible, you don't need to install special
software on the client or server.
MySQL's Connector/J driver is a Type 4 driver.

Pros
 No additional client software required.
 Direct communication with database server.

Cons
 May require additional configuration for Internet use.
Adding Driver 25

For other drivers, we need to download .jar or .zip

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
file and add to Library folder of application
 If you are using Java DB, it already comes with a JDBC driver.
 If you are using MySQL, add Connector/J.
 If you are using Oracle, add oracle JDBC driver.
 If you are using PostgreSQL, add postgresql JDBC driver.
In NetBeans,
1. Right click on the project name
2. Select “Properties” in the drop down menu
3. Select “Libraries” in JAR/Folder” button
 To use your JDBC driver, you must first load and register it
using JDBC driver registration.
Advanced Programming Chapter Three:
26

Database Connectivity
Thursday, March 13, 2025
Adding Driver in NetBeans
Loading JDBC Driver 27
A driver is a concrete class that implements the

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
java.sql.Driver interface.
Driver names of popular database management
systems are in the following table.

Database Driver Name


com.mysql.jdbc.Driver
MySQL
com.mysql.cj.jdbc.Driver
Oracle oracle.jdbc.driver.OracleDriver
JavaDB org.apache.derby.jdbc.ClientDriver
Access sun.jdbc.odbc.JdbcOdbcDriver
PostGreSQL postgresql.Driver
SQL Server 2012 com.microsoft.jdbc.sqlserver.SQLServerDriver
Loading JDBC Driver 28

 Three alternate techniques are available

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
1. Class.forName(String driverName).newInstance()
This statement causes the driver class to be loaded, thereby
executing a static initializer that registers the driver.
ClassNotFoundException is will be thrown and it has to be
handled to caught unknown driver name
E.g., Class.forName("com.mysql.jdbc.Driver");
2. DriverManager.registerDriver(Driver driverName)
Registers driver object to DriverManager
To remove a registered Driver from DriverManager use
DriverManager.deregisterDriver(Driver driverName)
method.
E.g., DriverManager.registerDriver(new com.mysql.jdbc.Driver());
3. System.setProperty("jdbc.drivers", String driverName)
Adds the driver classes to the jdbc.drivers property.
E.g., System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
Advanced Programming Chapter Three:
29

Database Connectivity
Thursday, March 13, 2025
Loading JDBC Driver Example
Access Loaded JDBC Driver 30

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 To access loaded drivers
 DriverManager.getDriver(String URL) : returns Driver object loaded
based on connection string/URL
 E.g., getting MySQL driver:

o Driver drivers = DriverManager.getDriver(“jdbc:mysql//localhost/db");

 DriverManager.getDrivers(): returns Enumeration object for all


discovered drivers.
Advanced Programming Chapter Three:
31

Database Connectivity
Thursday, March 13, 2025
Step 2: Establishing
connection
Define Connection URL 32
 JDBC URLs provide a way to identify a database.

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 JDBC URL is database specific.
 Syntax: jdbc:<subprotocol>:<subname>
 jdbc: is Protocol used to access database
 Subprotocol: indicates which vendor-specific protocol to use when
connecting to the database. Can be any of mysql, oracle, odbc, postgres,
sqlserver, etc.
 Subname: value indicates the data source, or database, you want to
connect with. It is the logical name of the database on your database server. Usually
contains database server address, port and database name.

 Example
 jdbc:mysql//hostname/databaseName
 jdbc:oracle:thin@hostname:portnumber:databaseName
Some Popular JDBC URLS 33

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
RDBMS Database URLs

MySQL jdbc:mysql://hostname/databaseName

Oracle jdbc:oracle:thin@hostname:portnumber:databaseName

JavaDB jdbc:derby://localhost:1527/databaseName

Access jdbc:odbc:databaseName
PostGreSQL jdbc:postgres://host/database
SQL Server jdbc:sqlserver://[serverName[\instanceName][:portNumber]]
[;property=value[;property=value]]
Establishing Connection with 34
JDBC

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 JDBC uses DriverManager class or Driver interface for connecting to a
target data source/database included under java.sql package :

1. DriverManager: fully implemented class connects an application to a


data source, using specified by a database URL.
 When this class first attempts to establish a connection, it automatically
loads any JDBC 4.0 drivers found within the class path.

 DriverManager.getConnection() static method that returns Connection


object is used to establish a database connection.

2. Driver: represents driver object

 driverObject.connect() is used to establish connection to database URL


specified
2.1. Driver Manager 35
 DriverManager class use getConnection() methods in three

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
ways to establish connection:
 public static Connection getConnection(String url)
 URL parameter is database string uniquely specifies database
used.
 In this case, URL includes database URL, username and
password as single string.
 public static Connection getConnection(String url, Properties
info)
 loads connection parameters such as database username and
password from database.properties and connects to the
database.
 public static Connection getConnection(String url, String
user, String password)
 Loads connection through explicitly defined database username
2.1. Driver Manager Example 36

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
Example: Database: MySQL, database name: test, user: root,
password: null
Option 1: public static Connection getConnection(String url)

 Option 2: public static Connection getConnection(String url, Properties props)

 Option 3: public static Connection getConnection(String url, String username, String


password)
Advanced Programming Chapter Three:
37

Database Connectivity
Thursday, March 13, 2025
Driver Manager
Advanced Programming Chapter Three:
38

Database Connectivity
Thursday, March 13, 2025
Step-3 and 4: Creating and
Executing Statement
Creating Statement 39
 Statement objects allow you to execute basic SQL queries and retrieve the results through

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
the ResultSet class
 Used to create, retrieve, update & delete data (CRUD) or metadata from a table
 Three types of statements each reflecting a specific SQL statements
 Statement:
 Used to implement simple SQL statements with no parameters.
 Use the for general-purpose access to your database. Useful when you are using static SQL statements
at runtime.
 The Statement interface cannot accept parameters.
 PreparedStatement
 (Extends Statement): Used for precompiling SQL statements that might contain input parameters.
 Use the when you plan to use the SQL statements many times.
 The PreparedStatement interface accepts input parameters at runtime.
 CallableStatement:
 (Extends PreparedStatement.) Used to execute stored procedures that may contain both input and
output parameters.
 Use the when you want to access the database stored procedures.
 The CallableStatement interface can also accept runtime input parameters.
Statement interface 40

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Statement interface defines methods that are used to interact with
database via the execution of SQL statements.

 To create a Statement instance, call the createStatement() method on


the Connection object you have retrieved using the
DriverManager.getConnection()
Executing Statement 41

 TheStatement class has three methods for executing

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
statements:
 executeUpdate(Stringsql): SQL DML statements such as
insert, update, and delete and SQL DDL such as create,
alter or drop table
o Returns integer when executed
 executeQuery(String sql): for SQL SELECT statement
o Returns resultSet
 execute(String sql):
o Returns a boolean value of true if a ResultSet object can be retrieved;
otherwise, it returns false.
o Used to execute SQL DDL statements or when we need to use dynamic
SQL.
Executing Statement 42
(executeUpdate)

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Returns the number of rows affected by the execution of the
SQL statement.
 Used to execute SQL statements, for which you expect to
get a number of rows affected such as, CREATE, INSERT,
UPDATE, or DELETE statement.
Executing Statement 43
(executeQuery)

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Only used to execute SELECT query
 Returns ResultSet object
Prepared Statement interface 44
 PreparedStatement interface is used to execute a precompiled SQL

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
statement with or without parameters.

 The Prepared Statement interface is a sub-interface of Statement.

 To create a Statement instance, call the prepareStatement(String


SQL) method on the Connection object you have retrieved using of the
DriverManager.getConnection()

 Syntax:
Prepared Statement 45
 It has three main uses

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Create parameterized statements such that data for parameters can
be dynamically substituted

 Create statements where data values may not be character strings

 Precompiling SQL statements to avoid repeated compiling of the


same SQL statement

 If parameters for the query are not set the driver returns an SQL
Exception

 Only the no parameters versions of executeUpdate() and


executeQuery() allowed with prepared statements.
Prepared Statement 46
 All parameters in JDBC are represented by the ? symbol, which is known as

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
the parameter marker.

 We must supply values for every parameter before executing the SQL

statement.

 setXXX(int position, XXX value) methods bind values to the parameters, where

XXX 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 SQLException.

 Each parameter marker is referred by its ordinal position.

 The first marker represents position 1, the next position 2, and so forth.
Advanced Programming Chapter Three:
47

Database Connectivity
Thursday, March 13, 2025
Data Types Mapping
Prepared Statement 48

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 For the above example parameter initialization is defined
as,
 setString (1, “hu-0210/10”); // for id
 setInt (2, 28); //for name
 Others
 setDouble(int position, xxx value)
Executing Prepared 49
Statement

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 All method in Statement such as execute(), executeUpdate()
and executeQuery() works for PreparedStatement, but
because pre-compilation feature the methods has no
parameter.
Advanced Programming Chapter Three:
50

Database Connectivity
Thursday, March 13, 2025
Executing Prepared statement
(Execute Update)
Advanced Programming Chapter Three:
51

Database Connectivity
Thursday, March 13, 2025
Executing Prepared statement
(execute Query)
Callable Statement interface 52
 Designed to execute SQL-stored procedures.

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 A CallableStatement object is created using the prepareCall(String call)
method in the Connection interface.
 Syntax:
 CallableStatement callableStatement
=connectionObject.prepareCall(
"{call sampleProcedure(?, ?, ?)}");
 {call sampleProcedure(?, ?, ...)} is referred to as the SQL escape syntax,
which signals the driver that the code within it should be handled differently.
 The driver parses the escape syntax and translates it into code that the database
understands.
 The call is translated to the string BEGIN sampleProcedure(?, ?, ?); END and
passed to an database for execution.
 We can call functions also.
 The syntax to create an SQL callable statement for a function is:
{? = call functionName(?, ?, ...)}
Callable Statement 53

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 The String variable SQL, represents the stored procedure, with parameter
placeholders.
 Using the CallableStatement objects is much like using the
PreparedStatement objects.
 You must bind values to all the parameters before executing the statement,
or you will receive an SQLException
 Binding value is same with PreparedStatement
 cstmt.setString(1, “HU-0123/10”), cstmt.setInt (2, 30).
Overview of Stored 54
Procedures

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 A stored procedure is a segment of declarative SQL
statements stored inside the database catalog. A stored
procedure can be invoked by triggers, other stored
procedures, and applications such as Java, Python, PHP.
Stored Procedures 55
 Why stored procedure?

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 They allow modular programming.
 They allow faster execution.
 They can reduce network traffic.
 They can be used as a security mechanism.
 Advantages of Stored Procedures
 Encapsulation & Reuse
 Transaction Control
 Standardization
 Disadvantages
 Database specific (lose independence)
 Callable statements provide means of using stored procedures in the
database
Stored Procedure 56
 Stored Procedures must follow certain rules

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Names of the stored procedures and parameters must be legal
 Parameter types must be legal supported by database
 Each parameter must have one of In, Out or Inout modes
 Example // Creating a stored procedure using SQL
 CREATE PROC procProductsList AS SELECT * FROM Products;
 CREATE PROC procProductsDeleteItem(inProductsID LONG) AS DELETE FROM Products
WHERE ProductsID = inProductsID;“
 CREATE PROC procProductsAddItem(inProductName VARCHAR(40),
inSupplierID LONG, inCategoryID LONG) AS INSERT INTO Products (ProductName,
SupplierID, CategoryID) Values (inProductName, inSupplierID, inCategoryID);"
 CREATE PROC procProductsUpdateItem(inProductID LONG, inProductName VARCHAR(40))
AS UPDATE Products SET ProductName = inProductName WHERE ProductID =
inProductID;"
 Usage: procProductsUpdateItem(1000, “My Music”)
Stored Procedures in MySQL 57
 Since MySQL version 5.0, stored procedures, stored functions, triggers,

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
and events features are added to the MySQL database engine to make it
more flexible and powerful.

 The first command is DELIMITER $, which is not related to the stored


procedure syntax.
 The DELIMITER statement changes the standard delimiter which is
semicolon ( ; ) to another.
 Following the END keyword, we use the delimiter $ to indicate the end of the
stored procedure.
 The last command ( DELIMITER; ) changes the delimiter back to the
semicolon (;)
Stored Procedures in MySQL 58

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 We use the CREATE PROCEDURE statement to create a new stored
procedure.
 We specify the name of stored procedure after the CREATE PROCEDURE
statement.

 In this case, the name of the stored procedure is PROCEDURE_NAME.

 We put the parentheses after the name of the stored procedure.

 The section between BEGIN and END is called the body of the
stored procedure.
Stored Procedures in MySQL 59

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 The syntax of defining a parameter in the stored procedures is as
follows:

 Mode:
 IN: is the default mode. When you define an IN parameter in a stored procedure, the
calling program has to pass an argument to the stored procedure.

 OUT: the value of an OUT parameter can be changed inside the stored procedure and its
new value is passed back to the calling program.
 INOUT: is a combination of IN and OUT parameters. It means that the calling program may pass
the argument, and the stored procedure can modify the INOUT parameter, and pass the new value

back to the calling program.

 Invoking procedure:
Advanced Programming Chapter Three:
60

Database Connectivity
Thursday, March 13, 2025
Stored Procedures in MySQL
Example 1
Advanced Programming Chapter Three:
61

Database Connectivity
Thursday, March 13, 2025
Stored Procedures in MySQL
Example 2
Advanced Programming Chapter Three:
62

Database Connectivity
Thursday, March 13, 2025
Executing Callable Statement
Example
Advanced Programming Chapter Three:
63

Database Connectivity
Thursday, March 13, 2025
Step-5: Processing Result
ResultSet 64
 The SQL statements that read data from a database query, return the

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
data in a result set.

 The SELECT statement is the standard way to select rows from a


database and view them in a result set.

 The java.sql.ResultSet interface represents the result set of a


database query.

 ResultSet is a Java object that contains the results of executing


an SQL query.
 In other words, it contains the rows that satisfy the conditions of the
query.

 The data stored in a ResultSet object is retrieved through a set of get


ResultSet: Cursors 65
 When the executeQuery method returns the ResultSet the cursor is

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
placed before the first row of the data
 Cursor refers to the set of rows returned by a query and is positioned on the row that is
being accessed

 To move the cursor to the first row of data next() method is invoked on the resultset

 If the next row has a data the next() results true else it returns false and the
cursor moves beyond the end of the data

 First column has index 1, not 0

 The following are methods to move the cursor:


 next: Moves the cursor forward one row.

 Returns true if the cursor is now positioned on a row and false if the cursor is
positioned after the last row.
ResultSet: Cursors 66
 first: Moves the cursor to the first row in the ResultSet object.

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Returns true if the cursor is now positioned on the first row and false if the ResultSet
object does not contain any rows.

 last: Moves the cursor to the last row in the ResultSet object.
 Returns true if the cursor is now positioned on the last row and false if the ResultSet
object does not contain any rows.

 beforeFirst: Positions the cursor at the start of the ResultSet object, before the first
row.
 If the ResultSet object does not contain any rows, this method has no effect.

 afterLast: Positions the cursor at the end of the ResultSet object, after the last row.
 If the ResultSet object does not contain any rows, this method has no effect.

 relative(int rows): Moves the cursor relative to its current position.


ResultSet: Get Data 67

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 ResultSet provides various access methods that take a column index or column
name and returns the data
 Data returned from an SQL query are JDBC data types, and you must convert them to Java
data types before you can use the information in your application.

 A ResultSet object provides the getXXX() method to perform this conversion.


 The XXX placeholder represents the Java data type you wish to retrieve.

 Depending on the data numerous functions exist


 getShort(), getInt(), getLong()

 getFloat(), getDouble()

 getClob(), getBlob(),

 getDate(), getTime(), getArray(), getString()


ResultSet: ResultSet Type 68
 ResultSet obtained from the statement created using the no result set argument is:

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Type forward only (non-scrollable)

 Not updateable

 To create a scrollable ResultSet the following statement constructor is required


 createStatement(int resultSetType, int resultSetConcurrency);

 prepareStatement(String sql, int resultSetType, int

resultSetConcurrency);
 prepareCall(String sql(call), int resultSetType, int resultSetConcurrency);

 ResultSetType determines whether it is scrollable. It can have the following values:

 ResultSet.TYPE_FORWARD_ONLY

 ResultSet.TYPE_SCROLL_INSENSITIVE (Unaffected by changes to


underlying database)
ResultSet: ResultSet 69

Concurrency
ResultSetConcurrency determines whether data is updateable. Its possible

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
values are:
 CONCUR_READ_ONLY: which creates a read-only result set. This is the default.

 CONCUR_UPDATEABLE: which creates an updateable result set

 Position the cursor  ResultSet.updateXXX(col, new_value) 


ResultSet.updateRow()
 Not all database drivers support these functionalities

 Note:
 resultSetType indicates how scrollable, and how sensitive to data changes

 resultSetConcurrency creates an updateable result set,


JDBC - Batch Processing 70
 Performance and data consistency are the primary motives to do batch

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
processing.

 By using batch processing, these queries can be sent to the database in one
call, thus improving performance.

 Steps for Batch Processing using Prepared Statement

1. Create SQL statements with placeholders.

2. Create PrepareStatement object using prepareStatement() method.

3. Set auto-commit to false using setAutoCommit().

4. Add as many as SQL statements you like into batch using addBatch() method on
created statement object.

5. Execute all the SQL statements using executeBatch() method on created statement
object.
Advanced Programming Chapter Three:
71

Database Connectivity
Thursday, March 13, 2025
Example
Advanced Programming Chapter Three:
72

Database Connectivity
Thursday, March 13, 2025
Step-6: Closing Connection
Closing Connection 73
 Each machine has a limited number of connections

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
(separate thread)
 If connections are not closed the system will run out of resources
and freeze
 Syntax: public void close() throws SQLException

• Correct way (Use the finally clause)


• Naïve Way: try{
try { Connection conn =
Connection conn Driver.Manager.getConnection(url);
= DriverManager.getConnection(url); // JDBC Code
// Jdbc Code } catch (SQLException sqle) {
… sqle.printStackTrace();
} catch (SQLException sqle) { } finally {
sqle.printStackTrace(); try {
} conn.close();
conn.close(); } catch (Exception e) {
• SQL exception in the Jdbc code will prevent e.printStackTrace();
}
execution to reach conn.close() }
JDBC MetaData 74
 Metadata basically means the data that provide a structured description

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
about some other data.
 JDBC metadata API provides the means to retrieve that information through Java
code.

 Java Metadata information is useful for writing code that can adapt to several
database system or to the content of any database.
 creating a sort of generic interface that uses advanced database features to discover
database metadata at runtime.

 JDBC has two interfaces,

ResultSetMetaData: interface for obtaining information on a specific ResultSet.

DatabaseMetaData: interface for obtaining database-wide information.


 is data about database data or, the information about tables, views, column types, column
names, stored procedures, databases, database URL, username, JDBC driver name and data
Database MetaData 75

Thursday, March 13, 2025


Database Connectivity
Advanced Programming Chapter Three:
 Answers
 What tables exist in the database visible to the user?

 What username is being used by this connection?

 Is this database connection read-only?

 What keywords are used by the database that are not SQL2?

 Does the database support column aliasing?

 Are multiple result sets from a single execute() call supported?

 Are outer joins supported?

 What are the primary keys for a table?


Advanced Programming Chapter Three:
76

Database Connectivity
Thursday, March 13, 2025
Creating Database MetaData

Creating DatabaseMetaData


ResultSet MetaData 77

Thursday, March 13, 2025


Database Connectivity
Advanced
 getTableName() Returns the name of the table you queried. Returns a

String.

Programming
 getColumnCount() Returns the number of columns in the result set.

Returns an int.
 getColumnName(int n) Returns the name of a column at position n in the

Chapter
result set. Returns a String.
 getColumnType(int n) Returns the JDBC data type for a column at

Three:
position n of the result set. Returns an int.
 getColumnTypeName(int n) Provides the name of the column’s data

type as defined by the database. The parameter n is the column position


within the result set. Returns a String.
Advanced Programming Chapter Three:
78

Database Connectivity
Thursday, March 13, 2025
Creating ResultSet MetaData
Advanced Programming Chapter Three:
79

Database Connectivity
Thursday, March 13, 2025
End of Chapter 3

You might also like