Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

https://genuinenotes.

com
Unit-8/ Java Programming - II

Unit 8: JDBC (Java Database connectivity)


The success of any business depends on the information and data assets it possesses. Therefore it
is very important for a business to have a system for storing and retrieving data. Though files are
used for storing data, they are highly inefficient in many respects like the amount of data that can
be stored, retrieving the data and many more. In order for the businesses to be competent, they
need sophisticated systems for storing complex and heavy volume of data and at the same time
retrieve the data faster enough to process the data. One such systems are the so called Databases.
Databases typically form the back bone for any e-business company. Any enterprise application
usually queries the databases to store, manipulate and retrieve the data to fulfill user’s requests.
Therefore understanding the basic details of databases is very important for building enterprise
applications.
A database is an organized collection of data. There are many different strategies for organizing
data to facilitate easy access and manipulation. A database management system (DBMS)
provides mechanisms for storing, organizing, retrieving and modifying data form any users.
Database management systems allow for the access and storage of data without concern for the
internal representation of data.
Some popular relational database management systems (RDBMSs) are Microsoft SQL Server,
Oracle, Sybase, IBM DB2, Informix, PostgreSQL and MySQL. The JDK now comes with a
pure-Java RDBMS called Java DB—Oracles’s version of Apache Derby.
Java programs communicate with databases and manipulate their data using the Java Database
Connectivity (JDBC™) API. A JDBC driver enables Java applications to connect to a database
in a particular DBMS and allows you to manipulate that database using the JDBC API.

Database Basics
A database as the name suggests is a sophisticated system for storing the data. Databases store
the data in the form of tables with each table containing several records of data. Databases are
broadly categorized into two types as listed below:
 Single table databases and
 Multi table or relational databases.
A single table databases doesn’t mean that they have just one table. It will have several tables of
data and all the tables are independent of each other. The main drawback with these databases is
the lack of flexibility while retrieving the data. On the other hand in multi table databases, two or
more tables are related with other. This feature offers more flexibility and power to retrieve the
data. These databases are therefore called as relational databases. Most of the modern enterprises
use relational databases.
 A typical database will have ‘n’ number tables with each having ‘n’ number of records.
 A relational database can store the data in several tables that are related with each other
as shown below:

1 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

If you notice the above tables, they are related with each other by the common column SSN. The
two tables together represent the customer information. To pull the customer information, we
need to pull the data from both the tables based on the matching SSN.

Structured Query Language (SQL)


 Structured Query Language which is abbreviated as SQL is a standard query language for
working with relational databases.
 SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.
 SQL is the standard language for Relational Database System. All the Relational
Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase,
Informix, Postgres and SQL Server use SQL as their standard database language.
 SQL is required:
 To create new databases, tables and views
 To insert records in a database
 To update records in a database
 To delete records from a database
 To retrieve data from a database
 What SQL does?
 With SQL, we can query our database in a numbers of ways, using
English-like statements.
 With SQL, user can access data from relational database management
system.
 It allows user to describe the data.
 It allows user to define the data in database and manipulate it when
needed.
 It allows user to create and drop database and table.
 It allows user to create view, stored procedure, function in a database.
 It allows user to set permission on tables, procedure and view.

2 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Some SQL data types


Data-type Syntax Explanation
Integer INTEGER The integer data type is used to
specify an integer value.
Smallint SMALLINT The smallint data type is used to
specify small integer value.
Numeric NUMERIC(P,S) It specifies a numeric value. Here
'p' is precision value and 's' is
scale value.
Real REAL The real integer is used to specify
a single precision floating point
number.
Decimal DECIMAL(P,S) It specifies a decimal value. Here
'p' is precision value and 's' is
scale value.
Double DOUBLE It specifies double precision
precision PRECISION floating point number.
Float FLOAT(P) It specifies floating-point value
e.g. 12.3, 4.5 etc. Here, 'p' is
precision value.
Character CHAR(X) Here, 'x' is the character's number
to store.
Character VARCHAR2(X) Here, 'x' is the character's number
varying to store
Bit BIT(X) Here, 'x' is the number of bits to
store
Bit varying BIT VARYING(X) Here, 'x' is the number of bits to
store (length can vary up to x).
Date DATE It stores year, month and days
values.
Time TIME It stores hour, minute and second
values
Timestamp TIMESTAMP The timestamp data type is used to
store year, month, day, hour,
minute and second values.

3 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Time with TIME WITH TIME It is exactly same as time but also
time zone ZONE store an offset from UTC of the
time specified.
Timestamp TIMESTAMP with It is same as timestamp but also
with time TIME ZONE stores an offset from UTC of the
zone time specified.

SQL Commands

DDL - Data Definition Language


Data Definition Language is used to define the database structure or schema. DDL is also used to
specify additional properties of the data. The storage structure and access methods used by the
database system by a set of statements in a special type of DDL called a data storage and
definition language. These statements define the implementation details of the database schema,
which are usually hidden from the users.
Sr.No. Command & Description

1 CREATE

Creates a new table, a view of a table, or other object in the database.


2 ALTER

4 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Modifies an existing database object, such as a table.


3 DROP

Deletes an entire table, a view of a table or other objects in the database.

DML - Data Manipulation Language


DML is short name of Data Manipulation Language which deals with data manipulation and
includes most common SQL statements such SELECT, INSERT, UPDATE, DELETE, etc., and
it is used to store, modify, retrieve, delete and update data in a database.
Sr.No. Command & Description

1 SELECT

Retrieves certain records from one or more tables.


2 INSERT

Creates a record.
3 UPDATE

Modifies records.
4 DELETE

Deletes records.

DCL - Data Control Language


A Data Control Language is a syntax similar to a computer programming language used to
control access to data stored in a database (Authorization). In particular, it is a component of
Structured Query Language (SQL).
Sr.No. Command & Description

1 GRANT

Gives a privilege to user.


2 REVOKE

Takes back privileges granted from user.

5 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

TCL- Transaction Control Language


Transaction Control Language commands are used to manage transactions in the database. These
are used to manage the changes made by DML-statements. It also allows statements to be
grouped together into logical transactions.
COMMIT: Commit command is used to permanently save any transaction
into the database.
ROLLBACK: This command restores the database to last committed state.
It is also used with savepoint command to jump to a savepoint
in a transaction.
SAVEPOINT: Savepoint command is used to temporarily save a transaction so
that you can rollback to that point whenever necessary.

6 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Creating a Table – Inserting, Updating, Deleting records

Creating a table
 The SQL syntax for creating a table is shown below:
CREATE TABLE <TABLE NAME>
(
COLUMN 1 NAME COLUMN 1 TYPE,
COLUMN 2 NAME COLUMN 2 TYPE,
.
.
COLUMN N NAME COLUMN N TYPE
);
Using the above syntax, to create the customers table, the SQL query will be as shown bellow:
CREATE TABLE Customers
(
FirstName VARCHAR(50),
LastName VARCHAR (50),
SSN NUMERIC(10),
Age NUMERIC(10),
City VARCHAR (32),
State VARCHAR (2),
Country VARCHAR (32)
);
While creating table, it’s very important to mention the type of data that will be stored in various
columns. VARCHAR is a standard data type for storing text data. NUMERIC is used for storing
numbers. The numbers in parenthesis represent the maximum length of data that can be stored.
Likewise, there are several other data type
Inserting the data into the table
To insert the data into the tables, we use the INSERT query. A single insert query inserts one
record or row of data. Following is the sql syntax.
INSERT INTO <TABLE NAME> VALUES (COL1 DATA, COL2 DATA …. COL (N)
DATA);
Using the above syntax, we insert the record into customers table as
INSERT INTO Customers VALUES (‘Smith’, ‘John’, 123456, 20,
‘Vegas’, ‘CA’, ‘USA’);

7 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

 You can specify or ignore the column names while using INSERT INTO statement.
 To insert partial column values, you must have to specify the column names. But if you
want to insert all the column values, you can specify or ignore the column names.

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)


VALUES (value1, value2, value3,...valueN);

Here, column1, column2, column3,...columnN are the names of the columns in the table
into which you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are adding
values for all the columns of the table. But make sure the order of the values is in the
same order as the columns in the table
While using the INSERT sql,
 Every data must be separated by a comma,
 All the text data must be enclosed in single quotes,
 Numeric data must not be enclosed in single quotes.
Updating records in table
To update the data in an existing record, we use the UPDATE query statement. The syntax for
this query is shown below:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

Example:

UPDATE CUSTOMERS
SET FirstName = ‘Joe’, LastName = ‘Roberts’
WHERE
SSN = 123456

The above query will update all the customers firstname and lastname whose SSN equals to
123456.
Retrieving records from table
Retrieving the records is the most important database operation. We use the SELECT query to
retrieve the records. The syntax for this query is as shown below:
SELECT COL 1 NAME, COL2 NAME …… FROM <TABLE NAME> WHERE
<CONDITION>

8 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

If the query has no WHERE clause, then it retrieves the selected columns from all the records in
the table. Based on this, let’s see few cases here:
Case 1: Retrieve all the customers data
SELECT * from Customers;
In the above sql asterisk(*) means all columns of data. Since there is no WHERE clause in the
query, it will pull up all the records. The result of the above query is the entire table.
Case 2: Select all the customers who belong to the state of CA.
SELECT * FROM Customers WHERE State = ‘CA’;
The above query will retrieve those records whose state is CA
Case 3: Retrieve the first names and last names whose country is USA and state is CA (multiple
conditions)
SELECT firstName, lastName from Customers WHERE State=’CA’ AND
Country=’USA’;
Case 4: Let’s say we have the following two tables.

If you noticed the above two (Books and Authors) tables, they are joined together using the
ISBN column. If we need to pull the publisher, author, title and country (data in both the tables)
for a particular ISBN, we do so as shown below:
SELECT t1.Publisher, t1.Title, t2.Author, t2.Country from Books
t1, Authors t2 WHERE
t1.ISBN = t2.ISBN;

9 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Whenever we need to pull data from multiple tables, we need to use alias names for tables. In the
above query, t1 is the alias name for Books table, and t2 is the alias name for Authors table.
Therefore, all the columns in books table must be prefixed with “t1.” and columns in authors
table must be prefixed with “t2.” as shown below:
SELECT t1.Publisher, t1.Title, t2.Author, t2.Country
Now, look at the where clause. Since we need to pull the data if the ISBN in both the tables
match, the where clause will be as shown below:
WHERE t1.ISBN = t2.ISBN;
Deleting the records
To delete the records in the table we use DELETE query. The syntax for this query is shown
below:
DELETE FROM <TABLE NAME> WHERE <CONDITION>
For instance, to delete all the customers whose state is CA, the query will be,
DELETE FROM Customers where State=’CA’;
The above SQL deletes 3 records in the customers table. These are all the basic SQL operations
you need to know to work with any database.

I am sure things are pretty simple. With this basic knowledge of databases and SQL, we are now
ready to learn JDBC technology to access databases.

What is JDBC?
JDBC stands for Java Database Connectivity which is a technology that allows Java applications
to interact with relational databases and execute SQL queries against the databases
JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers
to connect with the database.
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database.
JDBC helps to write Java applications that manage these three programming activities:
 Connect to a data source, like a database
 Send queries and update statements to the database
 Retrieve and process the results received from the database in answer to your query

10 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executable, such as −
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).

All of these different executable are able to use a JDBC driver to access a database, and take
advantage of the stored data.

Figure 1 JDBC and Databases

The above figure should tell you the complete story. Java applications simply use JDBC API to
interact with any database.

11 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

How JDBC talks with Databases?


 Databases are proprietary applications that are created by noted companies like Oracle,
Microsoft and many more. These could be developed in any language like C, C++ etc by
these vendors.
 Every database will expose something called Driver through with one can interact with
database for SQL operations.
 A driver is like a gateway to the database.
 Therefore, for any Java application to work with databases, it must use the driver of
that database.

Database Drivers
 A driver is not a hardware device. It’s a software program that could be written in any
language.
 Every database will have its own driver program.
 Given a driver program of a particular database, the challenge is how to use it to talk with
database. To understand this, we need to know the different types of drivers.

Before JDBC, ODBC API was the database API to


ODBC (Open Database Connectivity) is connect and execute query with the database.
a standard database access method
developed by Microsoft Corporation. But, ODBC API uses ODBC driver which is written in C
ODBC makes it possible to access data language (i.e. platform dependent and unsecured). That
from any application, regardless of which is why Java has defined its own API (JDBC API) that
database management system (DBMS) is uses JDBC drivers (written in Java language).
handling the data o ODBC is hard to learn.
o ODBC has a few commands with lots of complex
options. The preferred style in the Java
programming language is to have simple and
intuitive methods, but to have lots of them.
o ODBC relies on the use of void* pointers and
other C features that are not natural in the Java
programming language.
o An ODBC-based solution is inherently less safe
and harder to deploy than a pure Java solution.

12 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

There are basically 4 different types of database drivers as described below:


1. JDBC-ODBC Bridge Driver (Type -1 driver)

Figure 2: Type -1 Driver

 This is also called as Type-1 driver


 As you can notice from the above figure, this driver translates the JDBC calls to ODBC
calls in the ODBC layer. The ODBC calls are then translated to the native database API
calls. Because of the multiple layers of indirection, the performance of the application
using this driver suffers seriously. This type of driver is normally used for training
purposes and never used in commercial applications. The only good thing with this driver
is that you can access any database with it.
 In simple words, with this driver for JDBC to talk with vendor specific native API,
following translations will be made
JDBC - > ODBC -> Native
 It’s a 2 step process.
 The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of
driver.
2. Partly Java and Partly Native Driver (Type -2 driver)

Figure 3: Type -2 Driver

13 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

 This is also called as Type-2 driver


 As the name suggests, this driver is partly built using Java and partly with vendor specific
API
 With this driver, the JDBC calls are translated to vendor specific native calls in just one
step. It completely eliminates the ODBC layer. Because of this ODBC layer elimination,
the applications using this driver perform better.
 The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
3. Intermediate Database access Driver Server (Type -3 Driver)

Figure 4: Type- 3 Driver

 This is also called as Type-3 driver


 If you look at the Type-2 driver configuration, we only access one database at a time.
However there will be situations where multiple Java programs need to access to multiple
databases. This is where Type-3 driver is used.
 It acts as a middleware for the applications to access several databases. The Type-3
configuration internally may use Type-2 configuration to connect to database
 IDS JDBC Driver is an example
4. Pure Java Drivers (Type -4 Drivers)

Figure 5: Type - 4 Driver

 These are called as Type-4 drivers.


 Because of the widespread usage of Java, to facilitate easy and faster access to databases
from Java applications, database vendors built the driver itself using Java like good

14 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

friends helping each other. This is really cool as it completely eliminates the translation
process.
 JDBC is Java based technology, and with the driver also written in Java, it can directly
invoke the driver program as if it were any other Java program.
 This is the driver that all the J2EE applications use to interact with databases.
 Because this is a Java to Java interaction, this driver offers the best performance.
 MySQL's Connector/J driver is a Type 4 driver.
Which Driver should be Used?
 If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred
driver type is 4.
 If your Java application is accessing multiple types of databases at the same time, type 3
is the preferred driver.
 Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet
for your database.
 The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.

Driver JAR Files


 You need to obtain the JAR file in which the driver for your database is located (e.g. for
Derby database, you need the file derbyclient.jar)
 Include the driver JAR file on the class path
 Launch programs from the command line with
java –classpath .;driverJar ProgramName

JDBC API
JDBC technology is nothing but an API. It is a set of classes and interfaces that our Java
programs use to execute the SQL queries against the database. The fundamental idea behind
JDBC is that, Java programs use JDBC API, and JDBC API will in turn use the driver to work
with the database.
Therefore, to work with MySQL database, we need to configure the JDBC with all the MySQL
information. This information is nothing but:
 Name of the MySQL driver class
 URL of the database schema.
In simple words, for a Java program to work with the database, we first need to configure JDBC
with the above database info and then make the Java program use the JDBC.
Few class and interfaces of JDBC API are as follows:

15 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

The JDBC™ 4.3 ( Released in September 21, 2017) API includes both the java.sql package,
referred to as the JDBC core API, and the javax.sql package, referred to as the JDBC Optional
Package API. This complete JDBC API is included in the Java™ Standard Edition (Java SE™),
version 7. The javax.sql package extends the functionality of the JDBC API from a client-side
API to a server-side API, and it is an essential part of the Java™ Enterprise Edition (Java
EE™) technology.

JDBC programming is the simplest of all. There is a standard process we follow to execute the
SQL queries. Following lists the basic steps involved in any JDBC program.
 Import necessary packages
 Load and Register the Driver
 Establish the connection to the database
 Create the statements( using Statement/ PreparedStatement/ CallableStatement)
 Execute the statements
 Process the results
 Close the statements
 Close the connection.

16 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Figure 6: Steps to connect database in java

 The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

Example: Class.forName("oracle.jdbc.driver.OracleDriver");
 The getConnection() method of DriverManager class is used to establish connection with
the database.

Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLException


2) public static Connection getConnection(String url,String name,String passwrd)
throws SQLException

Example to establish connection with the Oracle database

17 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",
"password");
 The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

Example to create the statement object


Statement stmt=con.createStatement();
 The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the records
of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException


Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

 By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection


con.close();

18 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Database URLs
Database URL Formulation
After you've loaded the driver, you can establish a connection using
the DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods −
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
Following table lists down the popular JDBC driver names and database URL.

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port


Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port


Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port


Number/databaseName

All the highlighted part in URL format is static and you need to change only the remaining part
as per your database setup.
When connecting to a database, you must use parameters like
 host names,
 port numbers, and
 database names.

Syntax: jdbc:subprotocol:other_parameters

19 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Subprotocol selects the specific driver for connecting to the database.


The format for the other parameters depends on the subprotocol used.
Examples (database name is Demo)
jdbc:derby://localhost:1527/Demo;create=true
jdbc:mariadb://localhost:3306/Demo

Connecting to MySQL Database via JDBC


 At first, Configure MySQL Database server in your PC.
 Configure MySQL Server properties
o NetBeans IDE comes bundled with support for the MySQL RDBMS. Before you
can access the MySQL Database Server in NetBeans IDE, you must configure the
MySQL Server properties.
o Right-click the Databases node in the Services window and choose Register
MySQL Server to open the MySQL Server Properties dialog box .

(Window ServicesDatabase)

Figure 7: MySQL Database Server Properties

o Confirm that the server host name and port are correct.

20 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Notice that the IDE enters localhost as the default server host name and 3306 as
the default server port number.
 Click the “Run Administration Tool” tab at the top of the dialog box.
The Admin Properties tab is then displayed, allowing you to enter information for
controlling the MySQL Server.
http://localhost/phpmyadmin/
o Create database and tables

 Create a Java Project


o Add the MySQL JDBC Driver

Because it is a JDBC project and we opt to connect to a MySQL database, we


need MySQL JDBC Driver. It is basically a vendor-specific Type 4 driver that
bridges the communication gap between our application and the database. If you
want to connect to any other database, look for that database-specific JDBC
driver. A JDBC Driver for almost all major databases (Oracle, PostgreSQL, and
so on) is available in the relevant vendor sites.
 Right-click the project name in the Projects tree view → Properties.
 Select Libraries from the Categoriestree view.
 Click the Add Library button. An Add Library window will appear.
If the MySQL JDBC Driver is not present in the available libraries
list, click the Import…button. Then, click the MySQL JDBC Driver
from the available libraries list.

21 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Figure 8: Adding MySQL JDBC Driver in NetBeans

 Note: The MySQL JDBC Driver is already shipped with NetBeans.


There is no need to install it separately. Other drivers, which may
not be shipped with NetBeans, may need to be imported as a
separate jar file. In such a case, use the Add JAR/Folder button to
import it in the current project.
 If the import is successful, the imported jar file will be shown in the
projects list (inside Libraries of that project)

For MySQL Connection:


 Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
 Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/mydb where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and mydb is the database name..
 Username: The default username for the mysql database is root.

22 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

 Password: Password is given by the user at the time of installing the mysql database.

Creating the Application


There a few thing common to Java code in implementing a JDBC application. The package that
contains all the required classes and interfaces for JDBC programming is java.sql. The
exceptions that may occur are handled by the object of the SQLException reference defined in
the same package.
 Connecting to the database

Database connection is established by creating a Connection object. The Connection is an


interface and the object that implements the Connection interface manages the connection
between Java and the database. A reference to the Connection object is created with the help of
the overloaded static method getConnection(), defined in the DriverManager class. One of the
overloaded getConnection() methods takes three parameters.
 Database URL of the format jdbc:mysql://hostname:portNumber/databaseName for
MySQL. This format may change when connecting to other databases.
 Database user name
 Database password
 Executing the SQL query

Next, we need an object reference to the Statement interface to submit SQL statements to the
database.
 Processing the query result

The result of the query fired through the Statement object is contained by an object of
the ResultSet interface.

Executing SQL statements


 For SELECT queries, use

ResultSet rs =
statement.executeQuery("SELECT * FROM
Books")
 Process ResultSet object using

while (rs.next())
{

23 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

// look at a row of the result set


}
 Inside each row, get field value using
String isbn = rs.getString(1); // using
column index
double price = rs.getDouble("Price"); //
using column name

Note: You can use execute method to execute arbitrary SQL statements Database column indices
start from 1
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
public boolean execute(String sql): is used to execute queries that may return multiple
results.
public int[] executeBatch(): is used to execute batch of commands.

Managing Connections, Statements, Result Set


Every Connection object can create one or more Statement objects. You can use the same
Statement object for multiple, unrelated commands and queries. A statement has at most one
open result set. When you are done using a ResultSet, Statement, or Connection, call the close
method immediately (in finally block). The close method of a Statement object automatically
closes the associated result set The close method of the Connection class closes all statements of
the connection.

24 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Example: (Using Statement)


package jdbc_practice;

//import required package

import java.sql.*;

class Example{

public static void main(String args[])throws Exception{

String className = "com.mysql.jdbc.Driver"; //mysql driver (mysql-connector)

String db_url ="jdbc:mysql://localhost:3306/java2lab";

String db_username="root";

String db_password="";

//registering the driver


Class.forName(className);

//establishing the connection

//getConnection() is the method of DriverManager which will give object of Connection

//remember Connection is an interface we cannot create object directly

Connection con =DriverManager.getConnection(db_url,db_username,db_password);

//Create statements

//remember Statement is also an interface

Statement stmt=con.createStatement();

//Execute query

String my_query= "insert into students values(5,'Ramesh','Thapa',9876007865,'Jhapa')";

//this will insert a row in table "students"

//and affected number of rows will be returned

25 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

int res = stmt.executeUpdate(my_query);

System.out.println(res +"row(s) inserted");

//closing statement

stmt.close();
//closing connection

con.close();

Reading the Data


This is the most important and widely performed operation. In order to retrieve the data, we use
the following method on the statement object:
public ResultSet executeQuery (String sql )
The above method takes the query and returns a ResultSet object that contains all the records
returned by the database. We should then iterate over it and display the data. To retrieve the data
from the ResultSet, there are several get methods available based on the type of the data.
 We use the executeQuery() method to execute the SELECT query. This method will
return a ResultSet object as shown below:
ResultSet rs = stmt.executeQuery(myquery);

 A resultset object can be imagined like a table of records with a pointer at the beginning
of the table as shown below:
 To read the records, we need to move the pointer to the record using the next() method
until the pointer reaches the end of the records. This is what the while loop does. Once
we are in the loop, we need to read the record that the pointer points using the get
methods.
 The get methods can either take the column number starting from 1 or the column name
itself.
 In our example, the column numbers have been used.
 Following are the most commonly used get methods:
public String getString() Used for VARCHAR columns
public int getInt() Used for NUMERIC columns
public Date getDate() Used for DATE columns.

26 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

 Instead of specifying the column numbers, we can also specify the column names as
shown below:
String firstName = rs.getString(“fname”);

27 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

package jdbc_practice;
import java.sql.*;
public class ReadFromTable {
public static void main(String[] args) {
String className = "com.mysql.jdbc.Driver";
String db_url = "jdbc:mysql://localhost:3306/java2lab";
String db_username = "root";
String db_password = "";
try{
Class.forName(className);
Connection con;
Con=
DriverManager.getConnection(db_url,db_username,db_password);
Statement stmt;
stmt = con.createStatement();
String myquery = "SELECT * FROM students";
ResultSet rs;
rs = stmt.executeQuery(myquery);

int rn;
long phn;
String fn,ln,adr;

while(rs.next())
{
rn =rs.getInt(1);
fn =rs.getString(2);
ln = rs.getString(3);
phn = rs.getLong(4);

28 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

adr = rs.getString(5);
System.out.println("Roll Number:"+rn+"\t"
+"First Name:"+fn+"\t"
+"Last Name:"+ln+"\t"
+"Phone Number:"+phn+"\t"
+"Address:"+adr+"\t"
);
}
stmt.close();
con.close();
} catch(Exception excp){
System.out.println(excp);
}
}
}

Trick: If the query is SELECT, use the executeQuery() method. For all other
queries (CREATE, INSERT, DELETE, UPDATE etc) use the executeUpdate() method.

29 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Commonly used methods of ResultSet interface


public boolean next() is used to move the cursor to
the one row next from the
current position.
public boolean previous() is used to move the cursor to
the one row previous from
the current position.
public boolean first() is used to move the cursor to
the first row in result set
object.
public boolean last() is used to move the cursor to
the last row in result set
object.
public boolean absolute(int row) is used to move the cursor to
the specified row number in
the ResultSet object.
public boolean relative(int row) is used to move the cursor to
the relative row number in
the ResultSet object, it may
be positive or negative.
public int getInt(int columnIndex) is used to return the data of
specified column index of
the current row as int.
public int getInt(String columnName) is used to return the data of
specified column name of
the current row as int.
public String getString(int columnIndex) is used to return the data of
specified column index of
the current row as String.
public String getString(String columnName) is used to return the data of
specified column name of
the current row as String.

30 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Some programming tasks:

Task1:
Write a java program that allows a user to insert values to a table of
particular database (Suppose database is in MySql server ). The program
should take the values to insert from console.

Task2:
WAP using JDBC to display the records from a table of given database (Suppose
database is in MySql server ). Assume the following table :
result(roll_no , course_name ,marks_obtained)

The program should read the roll number value from console and display the
corresponding record.

//Task1 Code
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class Task1 {
private final String DRIVER_NAME = "com.mysql.jdbc.Driver";
private final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
private final String DB_USERNAME = "root";
private final String DB_PASSWORD = "";

31 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

int rn;
String course;
float marks;
private void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String queryToFire = "INSERT INTO
result(roll_no,course_name,marks_obtained)" + "VALUES(" +this.rn
+","+"\'"+this.course+"\'"+","+this.marks+")";
Statement st;
st = con.createStatement();
int n;
n=st.executeUpdate(queryToFire);
System.out.println("Thank you "+ n+ " record is added!");
st.close();
con.close();
} catch (Exception e){
System.out.println(e);
}
}
private void getDataFromConsole(){
Scanner sc = new Scanner(System.in);
System.out.println("--Enter following informations--");
System.out.println("---Enter course name--- ");
course = sc.nextLine();
System.out.println("---Enter roll number--- ");
rn = sc.nextInt();
32 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

System.out.println("---Enter Marks--- ");


marks = sc.nextFloat();
}
public static void main(String[] args) {
Task1 t1 =new Task1();
t1.getDataFromConsole();
t1.connectMeAndFireQuery();
}
}

33 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

//Task2 Code
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class Task2 {
private final String DRIVER_NAME = "com.mysql.jdbc.Driver";
private final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
private final String DB_USERNAME = "root";
private final String DB_PASSWORD = "";
int rn;
String course;
float marks;
private void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String queryToFire = "SELECT course_name,marks_obtained"
+ " FROM result"
+" WHERE roll_no ="+this.rn;
Statement st;
st = con.createStatement();
ResultSet record;
record=st.executeQuery(queryToFire);
while(record.next()){
course = record.getString("course_name");
marks = record.getFloat("marks_obtained");

34 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

System.out.println(
"Roll No: "+rn+"\t "
+"Course Name: "+ course+ "\t"
+"Marks: "+marks
);
}
st.close();
con.close();

} catch (Exception e){


System.out.println(e);
}
}
private void getDataFromConsole(){
Scanner sc = new Scanner(System.in);
System.out.println("---Enter roll number--- ");
rn = sc.nextInt();
}

public static void main(String[] args) {


Task2 t2 =new Task2();
t2.getDataFromConsole();
System.out.println("----Result---");
t2.connectMeAndFireQuery();
}
}

35 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

36 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

PreparedStatement
Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data from your database.

Interfaces Recommended Use

Statement Use this for general-purpose access to your database. Useful


when you are using static SQL statements at runtime. The
Statement interface cannot accept parameters.

PreparedStatement Use this when you plan to use the SQL statements many
times. The PreparedStatement interface accepts input
parameters at runtime.

CallableStatement Use this when you want to access the database stored
procedures. The CallableStatement interface can also
accept runtime input parameters.

 The PreparedStatement interface is a subinterface of Statement. It is used to execute


parameterized query.
 If you want to execute a Statement object many times, it usually reduces execution time
to use a PreparedStatement object instead.
 We should use PreparedStatement when we plan to use the SQL statements many
times. The PreparedStatement interface accepts input parameters at runtime.
 The main feature of a PreparedStatement object is that, unlike a Statement object, it is
given a SQL statement when it is created.
 The usage of PreparedStatement is pretty simple. It involves three simple steps as listed
below:
1. Create a PreparedStatement
2. Populate the statement
3. Execute the prepared statement.
 The basic idea with PreparedStatement is using the ‘?’ symbol in the query where ever
the data is to be substituted and then when the data is available, replace the symbols with
the data.
Step1: To create a prepared statement we use the following method on the Connection
object as shown below:
PreparedStament prepareStatement (String sql );

37 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

The SQL query to be passed to the above method will look as shown below:
String myQuery = “INSERT INTO students VALUES ( ?, ?, ?, ?, ?)”;
Since we need to insert data into five columns, we used five question marks. If you
notice the query, there are no single quotes like we had in earlier examples. Once we
have the above SQL query , we create the prepared statement as shown below:
PreparedStatement stmt = con.prepareStatement ( myQuery );
Step 2: Now that we created a prepared statement, its time to populate it with the data.
To do this, we use the setXXX() which methods bind values to the parameters,
where XXX represents the Java data type of the value you wish to bind to the input
parameterr. If you forget to supply the values, you will receive an SQLException.
Example:
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
Always remember one thing. The numbers in the set methods denote the position of the
question mark symbol but not the column number in the table

38 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

The important methods of PreparedStatement interface are given below:

Method Description
public void setInt(int paramIndex, int value) sets the integer value
to the given
parameter index.
public void setString(int paramIndex, String value) sets the String value
to the given
parameter index.
public void setFloat(int paramIndex, float value) sets the float value to
the given parameter
index.
public void setDouble(int paramIndex, double value) sets the double value
to the given
parameter index.
public int executeUpdate() executes the query. It
is used for create,
drop, insert, update,
delete etc.
public ResultSet executeQuery() executes the select
query. It returns an
instance of ResultSet.

39 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Example of PreparedStatement that inserts the record

package jdbc_practice;
import java.sql.*;
public class PSExample1 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL ="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String myQuery = "INSERT INTO students VALUES(?,?,?,?,?)";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setInt(1, 101);
pstmt.setString(2,"Ratan");
pstmt.setString(3,"Yadav");
pstmt.setLong(4,984100000);
pstmt.setString(5, "Saptari");
int n;
n=pstmt.executeUpdate();
System.out.println("Thank you "+ n+ " record is
added!");
pstmt.close();
con.close();

40 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

} catch (Exception e){


System.out.println(e);
}
}
public static void main(String[] args) {
PSExample1 pse1 =new PSExample1();
pse1.connectMeAndFireQuery();
}
}

Example of PreparedStatement interface that retrieve the records of a table


package jdbc_practice;
import java.sql.*;
public class PSExample2 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String myQuery = "SELECT * FROM result";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
ResultSet rs;

41 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

rs=pstmt.executeQuery();
while(rs.next()){
int rn = rs.getInt(1);
String course = rs.getString(2);
float marks= rs.getFloat(3);
System.out.println(
"Roll No: "+rn+"\t "
+"Course Name: "+ course+ "\t"
+"Marks: "+marks
);
}
pstmt.close();
con.close();
} catch (Exception e){
System.out.println(e);
}
}
public static void main(String[] args) {
PSExample2 pse2 =new PSExample2();
pse2.connectMeAndFireQuery();
}
}

42 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Example of PreparedStatement interface that deletes the record

package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class PSExample3 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
int rn;
void getRoll(){
Scanner sc = new Scanner(System.in);
System.out.println("Whose data is to be deleted? Enter
Roll No: ");
rn = sc.nextInt();
}
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String myQuery = "DELETE FROM students WHERE roll_no =?
";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setInt(1, rn);
int n = pstmt.executeUpdate();

43 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

System.out.println("The record is deleted!");


pstmt.close();
con.close();
} catch (Exception e){
System.out.println(e);
}
}
public static void main(String[] args) {
PSExample3 pse3 =new PSExample3();
pse3.getRoll();
pse3.connectMeAndFireQuery();
}
}

44 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

More programming tasks:

Task3:
Write a java program using PreparedStatement that allows a user to
insert values to a table of particular database (Suppose database is in
MySql server ). The program should take the values to insert from
console as long as user want to add new record.

Task4:
WAP using PreparedStatement to display the records from a table of given database
(Suppose database is in MySql server ). Assume the following table :
salary(emp_id , emp_name ,emp_salary)

The program should read the employee id value from console and display the
corresponding record.

45 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

//Task3 code
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class Task3 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
static int count;
int rn;
String course;
Float marks;
void getData(){
Scanner sc1 = new Scanner(System.in);
System.out.println("Enter Course Name:");
course =sc1.nextLine();
System.out.println("Enter Roll Number:");
rn = sc1.nextInt();
System.out.println("Enter Marks:");
marks = sc1.nextFloat();
}
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);

46 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

String myQuery = "INSERT INTO result VALUES(?,?,?)";


PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setInt(1, this.rn);
pstmt.setString(2,this.course);
pstmt.setFloat(3,this.marks);
int n=pstmt.executeUpdate();
count+=n;
pstmt.close();
con.close();
} catch (ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
public static void main(String[] args) {
Task3 t3 =new Task3();
Scanner sc2 = new Scanner(System.in);
char addMore;
do{
t3.getData();
t3.connectMeAndFireQuery();
System.out.println("Do you want to add more
record?(y/n)");
addMore = sc2.next().charAt(0);
}while(addMore!='n');
System.out.println("Thank you! "+ count +" records are
added");
}
}

47 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

48 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

//Task4 code
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class Task4 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
int eid;
void getEmpID(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter Employee ID: ");
eid = sc.nextInt();
}
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String myQuery = "SELECT emp_name,emp_salary FROM salary
WHERE emp_id =?";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setInt(1,this.eid);
ResultSet rs;
rs = pstmt.executeQuery();
while(rs.next())
49 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

{
String name= rs.getString("emp_name");
double sal = rs.getDouble("emp_salary");
System.out.println("Employee ID = " +eid +"\t"
+ "Employee Name = "+ name+"\t"
+"Salary = "+sal
);
}

pstmt.close();
con.close();
} catch (Exception e){
System.out.println(e);
}
}
public static void main(String[] args) {
Task4 t4 =new Task4();
t4.getEmpID();
t4.connectMeAndFireQuery();
}
}

50 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Connection Pooling
 Establishing a database connection is a very resource-intensive process and involves a lot
of overhead.
 Connection pooling is a mechanism to create and maintain a collection of JDBC
connection objects. The primary objective of maintaining the pool of connection object is
to leverage re-usability. A new connection object is created only when there are no
connection objects available to reuse. This technique can improve overall performance of
the application
 Connection pooling mechanism manage the connections effectively and efficiently by
optimizing the usage of database connections
 The connection pooling program comes along when we download the drivers for a
particular database
 The way the connection pooling works is,
1. It initializes a pool of connections with the database.
2. When a connection is requested by the application, it returns a connection from
the pool.
3. The application after using the connection returns it back to the pool.

Figure 7: Connection Pooling

 Connection pooling will be implemented in such a way that all the details are hidden
behind the scenes. The only change we as application developers need to make is the way
we retrieve the connection object. Once we get a connection object, the rest of the
program will be the same.
 Connection pooling is usually used with large scale enterprise applications where
thousands of processes need to access the database at the same time. In such situations
the application server will be configured to use the connection pooling.

51 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II

Why should we close the database connection?


Usually, every database has limited number of connections. Let’s say a database supports only
10 connections, and if your program doesn't close the connection every time it ran, the 11th time
you run, database will refuse to give you a connection. If you don't close a connection after using
it, from database point of view somebody is still using the connection, and it will not reuse this
connection until the connection is closed. You need to shut down the database and restart it to
release all the connections which is not good.
So, always make sure you close the database connection.

52 Collected by Bipin Timalsina

https://genuinenotes.com

You might also like