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

Unit 4

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

Unit 4

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

UNIT-4

PostgreSQL Python: Connect To


PostgreSQL Database Server
Summary: in this tutorial, you will learn how to connect to the PostgreSQL database server
in the Python program using the psycopg database adapter.

Install the psycopg2 module


First, visit the psycopg2 package here.

Second, use the following command line from the terminal:

pip install psycopg2Code language: Shell Session (shell)

If you have downloaded the source package into your computer, you can use the setup.py as
follows:

python setup.py build


sudo python setup.py installCode language: Shell Session (shell)

Create a new database


First, log in to the PostgreSQL database server using any client tool such as pgAdmin or psql.

Second, use the following statement to create a new database named suppliers in the
PostgreSQL database server.

CREATE DATABASE suppliers;Code language: SQL (Structured Query Language) (sql)

Connect to the PostgreSQL database using the psycopg2


To connect to the suppliers database, you use the connect() function of the psycopg2
module.

The connect() function creates a new database session and returns a new instance of the
connection class. By using the connection object, you can create a new cursor to execute
any SQL statements.

To call the connect() function, you specify the PostgreSQL database parameters as a
connection string and pass it to the function like this:

conn = psycopg2.connect("dbname=suppliers user=postgres


password=postgres")Code language: SQL (Structured Query Language) (sql)
Or you can use a list of keyword arguments:

conn = psycopg2.connect(
host="localhost",
database="suppliers",
user="postgres",
password="Abcd1234")Code language: Python (python)

The following is the list of the connection parameters:

 database: the name of the database that you want to connect.


 user: the username used to authenticate.
 password: password used to authenticate.
 host: database server address e.g., localhost or an IP address.
 port: the port number that defaults to 5432 if it is not provided.

To make it more convenient, you can use a configuration file to store all connection
parameters.

The following shows the contents of the database.ini file:

[postgresql]
host=localhost
database=suppliers
user=postgres
password=SecurePas$1Code language: Shell Session (shell)

By using the database.ini, you can change the PostgreSQL connection parameters when
you move the code to the production environment without modifying the code.

Notice that if you git, you need to add the database.ini to the .gitignore file to not
committing the sensitive information to the public repo like github. The .gitignore file will
be like this:

database.iniCode language: CSS (css)

The following config() function read the database.ini file and returns connection
parameters. The config() function is placed in the config.py file:

#!/usr/bin/python
from configparser import ConfigParser

def config(filename='database.ini', section='postgresql'):


# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)

# get section, default to postgresql


db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1}
file'.format(section, filename))

return dbCode language: Python (python)

The following connect() function connects to the suppliers database and prints out the
PostgreSQL database version.

#!/usr/bin/python
import psycopg2
from config import config

def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()

# connect to the PostgreSQL server


print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)

# create a cursor
cur = conn.cursor()

# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')

# display the PostgreSQL database server version


db_version = cur.fetchone()
print(db_version)

# close the communication with the PostgreSQL


cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')

if __name__ == '__main__':
connect()
Code language: Python (python)

How it works.

 First, read database connection parameters from the database.ini file.


 Next, create a new database connection by calling the connect() function.
 Then, create a new cursor and execute an SQL statement to get the PostgreSQL
database version.
 After that, read the result set by calling the fetchone() method of the cursor object.
 Finally, close the communication with the database server by calling the close()
method of the cursor and connection objects.

Execute the connect.py file

To execute the connect.py file, you use the following command:

python connect.pyCode language: Shell Session (shell)

You will see the following output:

Connecting to the PostgreSQL database...


PostgreSQL database version:
('PostgreSQL 12.3, compiled by Visual C++ build 1914, 64-bit',)
Database connection closed.Code language: Shell Session (shell)

It means that you have successfully connected to the PostgreSQL database server.

Troubleshooting

The connect() function raises the DatabaseError exception if an error occurred. To see
how it works, you can change the connection parameters in the database.ini file.

For example, if you change the host to localhosts, the program will output the following
message:

Connecting to the PostgreSQL database...


could not translate host name "localhosts" to address: Unknown hostCode
language: Shell Session (shell)

The following displays error message when you change the database to a database that does
not exist e.g., supplier:

Connecting to the PostgreSQL database...


FATAL: database "supplier" does not existCode language: Shell Session (shell)

If you change the user to postgress, it will not be authenticated successfully as follows:

Connecting to the PostgreSQL database...


FATAL: password authentication failed for user "postgress"

Understanding psycopg2
In order to connect to a database that is already created in your system or on the Internet, you
will have to instruct Python how to detect it. In other words, you will have to tell Python the
database of your interest is a PostgreSQL database.

In Python, you have several options that you can choose from. In this case, we will use
psycopg2, probably the most popular PostgreSQL database adapter for Python. Psycopg2
requires a few prerequisites to work properly on your computer. Once you have installed
them (read the documentation for more information), you can install psycopg2 just like any
other Python packages:

pip install psycopg2

However, if you want to use psycopg2 straightforwardly, you could also install psycopg2-
binary, a stand-alone version of the package, not requiring a compiler or external libraries.
This is the preferred installation for new users.

pip install psycopg2-binary

Finally, if you are using Python in a Conda environment, you should install psycopg2 using
the Anaconda installation:

conda install -c anaconda psycopg2

Now that you’re all set, let’s create your first connection to your PostgreSQL session with
psycopg2!

Connecting Python to PostgreSQL


In order to use Python to interact with a PostgreSQL database, we need to make a connection.
This is done with the psycopg2 connect() function, which creates a new database session and
returns a new connection instance.

For this tutorial, we will connect with a database called “datacamp_courses” that is hosted
locally.

conn = psycopg2.connect(database = "datacamp_courses",


user = "datacamp",
host= 'localhost',
password = "postgresql_tutorial",
port = 5432)

The basic connection parameters required are:

 database. The database name.


 user. User name required to authenticate.
 password. Password used to authenticate.
 host. Database server address (in our case, the database is hosted locally, but it could
be an IP address).
 port. Connection port number (defaults to 5432 if not provided).

Creating a table in PostgreSQL


It’s time to create your first table in the “datacamp_courses” database. We want to create a
table with information about some of the courses in the DataCamp course catalog. The table
has the following schema:

The specification gives us quite a bit of information on the table's columns. The table's
primary key should be course_id (note that only this one is bold), and its data type should be
an integer. A primary key is a constraint that enforces the column values to be non-null and
unique. It lets you uniquely identify a specific or a set of instances present in the table.

The remaining columns provide information about the course name, the name of the course
instruction, and the topic of the course.

Before creating the table, it’s important to explain how the connection instance you’ve just
created works. In essence, the connection encapsulates a database session, and it allows you
to execute SQL commands and queries, such as SELECT, INSERT, CREATE, UPDATE,
OR DELETE, using the cursor() method, and to make changes persistent using the commit()
method.

Once you have created the cursor instance, you can send commands to the database using the
execute() method and retrieve data from a table using fetchone(), fetchmany(), or fetchall().

Finally, it’s important to close the cursor and the connection to the database whenever you’ve
finished your operations. Otherwise, they will continue to hold server-side resources. To do
so, you can use the close() method.

Below you can find the code to create the data_courses table:

# Open a cursor to perform database operations


cur = conn.cursor()
# Execute a command: create data_courses table
cur.execute("""CREATE TABLE datacamp_courses(
course_id SERIAL PRIMARY KEY,
course_name VARCHAR (50) UNIQUE NOT NULL,
course_instructor VARCHAR (100) NOT NULL,
topic VARCHAR (20) NOT NULL);
""")
# Make the changes to the database persistent
conn.commit()
# Close cursor and communication with the database
cur.close()
conn.close()
This is a very basic example on how to create tables on PostgreSQL, but things can get much
more complex. If you want to learn more about how to create a PostgreSQL database and
explore the structure, data types, and how to normalize databases, check out our Creating
PostgreSQL Database course.

Executing Basic PostgreSQL Queries in Python


The data_courses table is ready; now it’s time to use SQL to perform some basic queries!

INSERT

You may have noticed that the table has no values so far. To create records in the
data_courses table, we need the INSERT command.

cur = conn.cursor()

cur.execute("INSERT INTO data_courses(course_name, course_instructor,


topic) VALUES('Introduction to SQL','Izzy Weber','Julia')");

cur.execute("INSERT INTO data_courses(course_name, course_instructor,


topic) VALUES('Analyzing Survey Data in Python','EbunOluwa
Andrew','Python')");

cur.execute("INSERT INTO data_courses(course_name, course_instructor,


topic) VALUES('Introduction to ChatGPT','James Chapman','Theory')");

cur.execute("INSERT INTO data_courses(course_name, course_instructor,


topic) VALUES('Introduction to Statistics in R','Maggie Matsui','R')");

cur.execute("INSERT INTO data_courses(course_name, course_instructor,


topic) VALUES('Hypothesis Testing in Python','James Chapman','Python')");

conn.commit()
cur.close()
conn.close()

The resulting table looks like this:

course_id course_name course_instructor topic


1 Introduction to SQL Izzy Weber Julia
2 Analyzing Survey Data in Python EbunOluwa Andrew Python
3 Introduction to ChatGPT James Chapman Theory
4 Introduction to Statistics in R Maggie Matsui R
5 Hypothesis Testing in Python James Chapman Python

SELECT

Reading data in SQL databases is probably something you will do a lot in your data science
journey. This is generally called a SELECT query. For now, let's see how the table
data_courses is holding up.
We will call the classic SELECT * FROM database_name statement to read all the data
available on the table. Then, we will use the fetchall() method to fetch all the available
rows. Notice that PostgreSQL automatically creates a numerical index for the course_id
column.

cur = conn.cursor()
cur.execute('SELECT * FROM datacamp_courses;')
rows = cur.fetchall()
conn.commit()
conn.close()
for row in rows:
print(row)

(1, 'Introduction to SQL', 'Izzy Weber', 'Julia')


(2, 'Analyzing Survey Data in Python', 'EbunOluwa Andrew', 'Python')
(3, 'Introduction to ChatGPT', 'James Chapman', 'Theory')
(4, 'Introduction to Statistics in R', 'Maggie Matsui', 'R')
(5, 'Hypothesis Testing in Python', 'James Chapman', 'Python')

UPDATE

Data often comes with errors. You may have noticed in the previous section that the topic
associated with the course “Introduction to SQL” is Julia. After checking the information
about the course, we discovered the mistake. We need to change it and write “SQL” instead.
This can be done with the UPDATE statement, as follows:

cur = conn.cursor()
cur.execute("UPDATE data_courses SET topic = 'SQL' WHERE course_name =
'Introduction to SQL';")
conn.commit()
conn.close()

DELETE

Finally, you may want to delete one of the records in your table. For example, let’s delete the
course Introduction to Statistics in R:

cur = conn.cursor()
cur.execute("""DELETE from data_courses WHERE course_name = 'Introduction
to Statistics in R'""");
conn.commit()
cur.close()

Advanced PostgreSQL Queries in Python


In the previous section, we examined the most basic SQL queries. But there’s much to learn.
Let’s see some more advanced queries.

ORDER BY
Say you want to sort your database by the name of the instructor. You can use the ORDER BY
statement:

cur = conn.cursor()

cur.execute('SELECT * FROM data_courses ORDER BY course_instructor')


rows = cur.fetchall()
for row in rows:
print(row)
(2, 'Analyzing Survey Data in Python', 'EbunOluwa Andrew', 'Python')
(1, 'Introduction to SQL', 'Izzy Weber', 'SQL')
(3, 'Introduction to ChatGPT', 'James Chapman', 'Theory')
(4, 'Hypothesis Testing in Python', 'James Chapman', 'Python')

GROUP BY

You may want to perform some aggregate functions within different groups of data. For
example, you may be interested in calculating the number of courses by the different course
instructors. You can do this kind of operation with the GROUP BY function.

cur = conn.cursor()
cur.execute('SELECT course_instructor, COUNT(*) FROM data_courses GROUP BY
course_instructor')
rows = cur.fetchall()
for row in rows:
print(row)

('James Chapman', 2)
('Izzy Weber', 1)
('EbunOluwa Andrew', 1)

JOIN

Up to this point, we’ve only worked with the data_course table. But you only start
leveraging the full potential of relational databases, like PostgreSQL, when you work with
multiple tables at once.

The magic tool to combine multiple tables is the JOIN operation. Imagine that we have a
second table in our database called programming_languages that contains basic information
about the top programming languages for data science, including the name, the position in the
TIOBE Index, and the number of courses about the programming language in Datacamp. The
table looks like this:

language_id language_name course_number tiobe_ranking


1 SQL 31 8
2 Python 157 1
3 R 132 16
4 Julia 2 33
5 Scala 1 38
Imagine you want to merge the two tables to get the information of the courses, together with
the position of the language on the TIOBE index. We will use an INNER JOIN to get only the
information of the programming languages that appear in the datacamp_course table.

cur = conn.cursor()
cur.execute("""SELECT course_name, course_instructor, topic, tiobe_ranking
FROM datacamp_courses
INNER JOIN programming_languages
ON datacamp_courses.topic = programming_languages.language_name""")
rows = cur.fetchall()
for row in rows:
print(row)

('Introduction to SQL', 'Izzy Weber', 'SQL', 8)


('Analyzing Survey Data in Python', 'EbunOluwa Andrew', 'Python', 1)
('Hypothesis Testing in Python', 'James Chapman', 'Python', 1)

TRIGGERS and CURSORS

Triggers resemble stored procedures. A trigger can execute SQL and PL/SQL statements as a
unit and invoke stored procedures. However, procedures and triggers are activated in
different ways. A cursor is a Database object that retrieves rows from the database row-by-
row, but it is primarily used to reduce network traffic. In addition to traversing records in a
database, cursors facilitate data retrieval, addition and deletion of records.

What is the Cursor in PL/SQL?


A cursor is just a pointer to the current context region. Context area is a memory region
produced by Oracle during the processing of a SQL query. Therefore, the cursor is
responsible for retaining the rows returned by a SQL query. PL/SQL manages the context
region with the aid of the cursor. The active set is essentially the set of rows held by the
cursor. There are two kinds of cursors: implicit cursor and explicit cursor.

Advantages:

 They are useful for processing each row individually and validating each row
individually.
 Utilizing cursors allows for enhanced concurrent control.
 While loops execute more slowly than cursors.

Features:

 A cursor keeps track of the current position in the result set. It enables you to perform
multiple operations row by row against a result set, either with or without returning to
the original table.

Disadvantages:

 They use additional resources each time, which may result in a network round trip.
 An increase in the number of network round trips can degrade performance and slow
down the network.

What is the Trigger in SQL?


A Trigger is a program automatically performed in reaction to certain events, such as
database changes. DDL and DML statements, as well as any Database activity, are a few of
the events for their execution. Thus, triggers are saved in the database and activated when
certain circumstances are met. Consequently, they may be defined for any schema, table,
view, etc. BEFORE INSERT, AFTER INSERT, BEFORE UPDATE, AFTER UPDATE,
BEFORE DELETE, and AFTER DELETE are the six kinds of triggers.

Features:

 Event Type - It must be declared to process the UPDATE event.


 Object Scope- It must be declared to handle the UPDATE event only on the user
password table.
 Statement Body - It must have a statement body to determine whether or not the
password has actually been changed.

Advantages:

 They aid in monitoring all database modifications.


 Additionally, they aid in upholding the integrity limitations.

Disadvantages:

 They are very difficult to see, making debugging tough.


 Using triggers excessively or implementing complicated code inside a trigger might
hinder performance.

Cursor vs. Trigger


Cursor Trigger
 It is a pointer which is used to control  It is a program which gets executed
the context area and also to go through in response to occurrence of some
the records in the database. events.

 A cursor can be created within a trigger


 A trigger cannot be created within a
by writing the declare statement inside
cursor.
the trigger.

 It gets created in response to execution


of SQL statement thus it is not  It is a previously stored program.
previously stored.

 The main function of the cursor is  The main function of trigger is to


retrieval of rows from the result set one
maintain the integrity of the database.
at a time (row by row).

 A trigger is executed in response to a


 A cursor is activated and thus created in
DDL statement, DML statement or
response to any SQL statement.
any database operation.

Triggers can be defined on the table, view, schema, or database with which the event is
associated.

Benefits of Triggers

Triggers can be written for the following purposes −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Creating Triggers
The syntax for creating a trigger is −

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Where,

 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing


trigger with the trigger_name.
 {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
 [OF col_name] − This specifies the column name that will be updated.
 [ON table_name] − This specifies the name of the table associated with the trigger.
 [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
 [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
 WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.

Example

To start with, we will be using the CUSTOMERS table we had created and used in the
previous chapters −

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+

The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

Trigger created.

The following points need to be considered here −

 OLD and NEW references are not available for table-level triggers, rather you can use
them for record-level triggers.
 If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
 The above trigger has been written in such a way that it will fire before any DELETE
or INSERT or UPDATE operation on the table, but you can write your trigger on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.

Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

When a record is created in the CUSTOMERS table, the above create trigger,
display_salary_changes will be fired and it will display the following result −

Old salary:
New salary: 7500
Salary difference:

Because this is a new record, old salary is not available and the above result comes as null.
Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE
statement will update an existing record in the table −

UPDATE customers
SET salary = salary + 500
WHERE id = 2;

When a record is updated in the CUSTOMERS table, the above create trigger,
display_salary_changes will be fired and it will display the following result −

Old salary: 1500


New salary: 2000
Salary difference: 500

CURSORS

A cursor is a pointer to this context area. It contains all information needed for processing the
statement. In PL/SQL, the context area is controlled by Cursor. A cursor contains information
on a select statement and the rows of data accessed by it.

A cursor is used to referred to a program to fetch and process the rows returned by the SQL
statement, one at a time. There are two types of cursors:

 Implicit Cursors
 Explicit Cursors

1) PL/SQL Implicit Cursors


The implicit cursors are automatically generated by Oracle while an SQL statement is
executed, if you don't use an explicit cursor for the statement.

These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.

Orcale provides some attributes known as Implicit cursor's attributes to check the status of
DML operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and
%ISOPEN.

For example: When you execute the SQL statements like INSERT, UPDATE, DELETE
then the cursor attributes tell whether any rows are affected and how many have been
affected. If you run a SELECT INTO statement in PL/SQL block, the implicit cursor attribute
can be used to find out whether any row has been returned by the SELECT statement. It will
return an error if there no data is selected.

The following table soecifies the status of the cursor with each of its attribute.

Attribute Description
Its return value is TRUE if DML statements like INSERT, DELETE and
%FOUND UPDATE affect at least one row or more rows or a SELECT INTO
statement returned one or more rows. Otherwise it returns FALSE.
Its return value is TRUE if DML statements like INSERT, DELETE and
%NOTFOUND UPDATE affect no row, or a SELECT INTO statement return no rows.
Otherwise it returns FALSE. It is a just opposite of %FOUND.
It always returns FALSE for implicit cursors, because the SQL cursor is
%ISOPEN
automatically closed after executing its associated SQL statements.
It returns the number of rows affected by DML statements like INSERT,
%ROWCOUNT
DELETE, and UPDATE or returned by a SELECT INTO statement.

PL/SQL Implicit Cursor Example


Create customers table and have records:

ID NAME AGE ADDRESS SALARY


1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000

Let's execute the following program to update the table and increase salary of each customer
by 5000. Here, SQL%ROWCOUNT attribute is used to determine the number of rows
affected:

Create procedure:
1. DECLARE
2. total_rows number(2);
3. BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated ');
11. END IF;
12. END;
13. /

Output:

6 customers updated
PL/SQL procedure successfully completed.

Now, if you check the records in customer table, you will find that the rows are updated.

1. select * from customers;

ID NAME AGE ADDRESS SALARY


1 Ramesh 23 Allahabad 25000
2 Suresh 22 Kanpur 27000
3 Mahesh 24 Ghaziabad 29000
4 Chandan 25 Noida 31000
5 Alex 21 Paris 33000
6 Sunita 20 Delhi 35000

2) PL/SQL Explicit Cursors


The Explicit cursors are defined by the programmers to gain more control over the context
area. These cursors should be defined in the declaration section of the PL/SQL block. It is
created on a SELECT statement which returns more than one row.

Following is the syntax to create an explicit cursor:

Syntax of explicit cursor


Following is the syntax to create an explicit cursor:

1. CURSOR cursor_name IS select_statement;;

Steps:
You must follow these steps while working with an explicit cursor.
1. Declare the cursor to initialize in the memory.
2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.

1) Declare the cursor:


It defines the cursor with a name and the associated SELECT statement.

Syntax for explicit cursor decleration

1. CURSOR name IS
2. SELECT statement;

2) Open the cursor:


It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the
SQL statements into it.

Syntax for cursor open:

1. OPEN cursor_name;

3) Fetch the cursor:


It is used to access one row at a time. You can fetch rows from the above-opened cursor as
follows:

Syntax for cursor fetch:

1. FETCH cursor_name INTO variable_list;

4) Close the cursor:


It is used to release the allocated memory. The following syntax is used to close the above-
opened cursors.

Syntax for cursor close:

1. Close cursor_name;

PL/SQL Explicit Cursor Example


Explicit cursors are defined by programmers to gain more control over the context area. It is
defined in the declaration section of the PL/SQL block. It is created on a SELECT statement
which returns more than one row.
Let's take an example to demonstrate the use of explicit cursor. In this example, we are using
the already created CUSTOMERS table.

Create customers table and have records:

ID NAME AGE ADDRESS SALARY


1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000

Create procedure:

Execute the following program to retrieve the customer name and address.

1. DECLARE
2. c_id customers.id%type;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. CURSOR c_customers is
6. SELECT id, name, address FROM customers;
7. BEGIN
8. OPEN c_customers;
9. LOOP
10. FETCH c_customers into c_id, c_name, c_addr;
11. EXIT WHEN c_customers%notfound;
12. dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
13. END LOOP;
14. CLOSE c_customers;
15. END;
16. /

Output:

1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy