Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Basic CRUD Operations Using cx_Oracle, Part 5: Delete

DZone's Guide to

Basic CRUD Operations Using cx_Oracle, Part 5: Delete

In this post, we’re going to take a look at the D in CRUD: Delete. We use the cx_Oracle driver to delete some data in the database tables, using the connection object created in the Initial Setup section of the first post in this series.

· Database Zone
Free Resource

Read why times series is the fastest growing database category.

In this post, we’re going to take a look at the D in CRUDDelete.  We use the cx_Oracle driver to delete some data in the database tables, using the connection object created in the Initial Setup section of the first post in this series.

WARNING: PLEASE REVIEW ALL EXAMPLE CODE AND ONLY RUN IT IF YOU ARE SURE IT WILL NOT CAUSE ANY PROBLEMS WITH YOUR SYSTEM.

Helper Function

The helper function get_all_rows() encapsulates a select statement used to verify that the delete statements worked. The select functionality is covered in the R part of this series, so I won’t go into the details here.

def get_all_rows(label, data_type='people'):
  # Query all rows
  cur = con.cursor()
  if (data_type == 'pets'):
    statement = 'select id, name, owner, type from cx_pets order by owner, id'
  else:
    statement = 'select id, name, age, notes from cx_people order by id'
  cur.execute(statement)
  res = cur.fetchall()
  print(label + ': ')
  print (res)
  print(' ')
  cur.close()

Add this function to the top of your file.

Resetting the Data

To keep the examples clean and precise, we will reset the data at times.

Create a new file called reset_data.py with the following code and run it whenever you would like to reset the data. (Notice this version adds people and pet data not included in other sections.)

import cx_Oracle
import os
connectString = os.getenv('db_connect')
con = cx_Oracle.connect(connectString)
cur = con.cursor()

# Delete rows
statement = 'delete from cx_pets'
cur.execute(statement)

# Reset Identity Coulmn
statement = 'alter table cx_pets modify id generated BY DEFAULT as identity (START WITH 8)'
cur.execute(statement)

# Delete rows
statement = 'delete from cx_people'
cur.execute(statement)

# Reset Identity Coulmn
statement = 'alter table cx_people modify id generated BY DEFAULT as identity (START WITH 8)'
cur.execute(statement)

# Insert default rows
rows = [(1, 'Bob', 35, 'I like dogs'),
        (2, 'Kim', 27, 'I like birds'),
        (3, 'Cheryl', 23, 'I like horses'),
        (4, 'Bob', 27, 'I like rabbits'),
        (5, 'Stacey', 45, 'I like snakes'),
        (6, 'Pete', 23, 'I like cats'),
        (7, 'Pat', 36, 'I like dogs')]
cur.bindarraysize = 2
cur.setinputsizes(int, 20, int, 100)
cur.executemany("insert into cx_people(id, name, age, notes) values (:1, :2, :3, :4)", rows)
con.commit()

# Insert default rows
rows = [(1, 'Duke', 1, 'dog'),
        (2, 'Dragon', 2, 'bird'),
        (3, 'Sneaky', 5, 'snake'),
        (4, 'Red', 2, 'bird'),
        (5, 'Red', 3, 'horse'),
        (6, 'Buster', 1, 'dog'),
        (7, 'Fido', 7, 'cat')]
cur.bindarraysize = 2
cur.setinputsizes(int, 20, int, 100)
cur.executemany("insert into cx_pets (id, name, owner, type) values (:1, :2, :3, :4)", rows)
con.commit()

cur.close()

Boilerplate Template

The template we will be using is:

import cx_Oracle
import os
connectString = os.getenv('db_connect')
con = cx_Oracle.connect(connectString)

def get_all_rows(label, data_type='people'):
  # Query all rows
  cur = con.cursor()
  if (data_type == 'pets'):
    statement = 'select id, name, owner, type from cx_pets order by owner, id'
  else:
    statement = 'select id, name, age, notes from cx_people order by id'
  cur.execute(statement)
  res = cur.fetchall()
  print(label + ': ')
  print (res)
  print(' ')
  cur.close()

get_all_rows('Original Data', 'pets')

# Your code here

get_all_rows('New Data', 'pets')

For each exercise, replace the “# Your code here” line with your code.

Reset the data

First, let’s run reset_data.py to set up our data.

Simple Delete

We will perform a simple delete that removes a single record in the cx_people table.  These are the steps performed in the code snippet below.

  • Get a cursor object from our connection.  We will use this cursor to perform our database operations.
  • Prepare a SQL DELETE statement, deleting the cx_pets record with an id of 1.
  • Execute the statement using bind variables.  (see the R part of this series for an explanation of bind variables)
  • Commit the transaction.

When I run this code in my Python session, I see:

Image title

Original Data:
[(1, 'Duke', 1, 'dog'), (6, 'Buster', 1, 'dog'), (2, 'Dragon', 2, 'bird'), (4, 'Red', 2, 'bird'), (5, 'Red', 3, 'horse'), (3, 'Sneaky', 5, 'snake'), (7, 'Fido', 7, 'cat')]

New Data:
[(6, 'Buster', 1, 'dog'), (2, 'Dragon', 2, 'bird'), (4, 'Red', 2, 'bird'), (5, 'Red', 3, 'horse'), (3, 'Sneaky', 5, 'snake'), (7, 'Fido', 7, 'cat')]

Extra Fun 1

Delete all the birds.

Your results should be:

Image title

Original Data:
[(6, 'Buster', 1, 'dog'), (2, 'Dragon', 2, 'bird'), (4, 'Red', 2, 'bird'), (5, 'Red', 3, 'horse'), (3, 'Sneaky', 5, 'snake'), (7, 'Fido', 7, 'cat')]

New Data:
[(6, 'Buster', 1, 'dog'), (5, 'Red', 3, 'horse'), (3, 'Sneaky', 5, 'snake'), (7, 'Fido', 7, 'cat')]

Answer

cur = con.cursor()
statement = 'delete from cx_pets where type = :type'
cur.execute(statement, {'type':'bird'})
con.commit()

Reset the data

Now is a good time to run reset_data.py.

Boilerplate Change

Change the boilerplate get_all_rows statements to get people and pet data.

get_all_rows('Original People Data', 'people')
get_all_rows('Original Pet Data', 'pets')

# Your code here

get_all_rows('New People Data', 'people')
get_all_rows('New Pet Data', 'pets')

Deleting Records Referenced by Foreign Keys

If you are using integrity constraints in your database (of course you are, because then you let the database do some heavy lifting for you), you will sometimes need to change the way you process your changes.

In our design, we have a Foreign Key constraint in cx_pets that ensures if a pet has an owner, that owner exists.

This is the statement that creates the constraint in the Creating the Database Objects section of the Initial Setup post.

ALTER TABLE CX_PETS ADD CONSTRAINT FK_CX_PETS_OWNER FOREIGN KEY ("OWNER") REFERENCES "CX_PEOPLE" ("ID")
/

If we attempt to delete a record in cx_people that is referenced in cx_pets (Person has a pet,) we get an error.

cur = con.cursor()
statement = 'delete from cx_people where id = :id'
cur.execute(statement, {'id':1})
con.commit()

When I run this code in my Python session, I see:

Image title

Traceback (most recent call last):
 File "delete.py", line 25, in <module>
 cur.execute(statement, {'id':1})
cx_Oracle.IntegrityError: ORA-02292: integrity constraint (DD.FK_CX_PETS_OWNER)
violated - child record found

Before deleting the person you have to handle the pet (watch out for claws and teeth).

There are a few options here, depending on your database design:

  • If: pets are not required to have an owner and you only want to delete the person, not the pets.  Then: you can update the pets and set their owner to null.
  • If: pets are required to have an owner.  Then: you can delete the pets for the owner.

In either of the above scenarios, you can update the pets and set their owner to another person.

Bob is moving out of our area and his new apartment doesn’t allow pets, so he’s giving them to Kim.  Let’s use that last option here.

  • Get a cursor object from our connection.  We will use this cursor to perform our database operations.
  • Prepare a SQL UPDATE statement, changing owner to 2 (Kim) for the records with an owner of 1 (Bob).  Updating is covered in the U part of this series.
  • Execute the statement using bind variables.
  • Prepare a SQL DELETE statement, deleting records with an id of 1 (Bob).
  • Execute the statement using bind variables. (see the R part of this series for an explanation of bind variables)
  • Commit the transaction.
cur = con.cursor()

statement = 'update cx_pets set owner = :1 where owner = :2'
cur.execute(statement, (2, 1))

statement = 'delete from cx_people where id = :id'
cur.execute(statement, {'id':1})
con.commit()

When I run this code in my Python session, I see:

Image title

Original People Data:
[(1, 'Bob', 35, 'I like dogs'), (2, 'Kim', 27, 'I like birds'), (3, 'Cheryl', 23, 'I like horses'), (4, 'Bob',
27, 'I like rabbits'), (5, 'Stacey', 45, 'I like snakes'), (6, 'Pete', 23, 'I like cats'), (7, 'Pat', 36, 'I like dogs')]

Original Pet Data:
[(1, 'Duke', 1, 'dog'), (6, 'Buster', 1, 'dog'), (2, 'Dragon', 2, 'bird'), (4, 'Red', 2, 'bird'), (5, 'Red', 3, 'horse'), (3, 'Sneaky', 5, 'snake'), (7, 'Fido', 7, 'cat')]

New People Data:
[(2, 'Kim', 27, 'I like birds'), (3, 'Cheryl', 23, 'I like horses'), (4, 'Bob', 27, 'I like rabbits'), (5, 'Stacey', 45, 'I like snakes'), (6, 'Pete', 23, 'I like cats'), (7, 'Pat', 36, 'I like dogs')]

New Pet Data:
[(1, 'Duke', 2, 'dog'), (2, 'Dragon', 2, 'bird'), (4, 'Red', 2, 'bird'), (6, 'Buster', 2, 'dog'), (5, 'Red', 3, 'horse'), (3, 'Sneaky', 5, 'snake'), (7, 'Fido', 7, 'cat')]

When you change data it’s a good idea to verify the number of affected rows.  This is covered in the R part of this series.

Extra Fun 2

Due to a zoning change, snakes are no longer allowed in our area.  Stacey has decided to move and take Sneaky with her.

Let's fix our data.

Your results should be:

Image title

Original People Data:
[(2, 'Kim', 27, 'I like birds'), (3, 'Cheryl', 23, 'I like horses'), (4, 'Bob', 27, 'I like rabbits'), (5, 'Stacey', 45, 'I like snakes'), (6, 'Pete', 23, 'I like cats'), (7, 'Pat', 36, 'I like dogs')]

Original Pet Data:
[(1, 'Duke', 2, 'dog'), (2, 'Dragon', 2, 'bird'), (4, 'Red', 2, 'bird'), (6, 'Buster', 2, 'dog'), (5, 'Red', 3, 'horse'), (3, 'Sneaky', 5, 'snake'), (7, 'Fido', 7, 'cat')]

New People Data:
[(2, 'Kim', 27, 'I like birds'), (3, 'Cheryl', 23, 'I like horses'), (4, 'Bob', 27, 'I like rabbits'), (6, 'Pete', 23, 'I like cats'), (7, 'Pat', 36, 'I like dogs')]

New Pet Data:
[(1, 'Duke', 2, 'dog'), (2, 'Dragon', 2, 'bird'), (4, 'Red', 2, 'bird'), (6, 'Buster', 2, 'dog'), (5, 'Red', 3, 'horse'), (7, 'Fido', 7, 'cat')]

Answer

cur = con.cursor()

statement = 'delete from cx_pets where owner = :owner'
cur.execute(statement, {'owner':5})

statement = 'delete from cx_people where id = :id'
cur.execute(statement, {'id':5})
con.commit()

Some other things you could try

  • Change the database constraints to delete or Null the child record on delete (a cascading delete).  Delete a person and let the database handle the children.
  • Remove the people who don’t have any pets.

Series Sections

Initial Setup
Create records
Retrieve records
Update records
Delete records

Learn how to get 20x more performance than Elastic by moving to a Time Series database.

Topics:
oracle ,python ,crud ,database

Published at DZone with permission of Blaine Carter. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}