DZone
Database Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Database Zone > Basic CRUD Operations Using cx_Oracle, Part 2: Retrieve

Basic CRUD Operations Using cx_Oracle, Part 2: Retrieve

In this post, we're going to take a look at the R in CRUD: Retrieve. We will be using the cx_Oracle driver to retrieve some data from the database tables, using the connection object created in the Initial Setup section of the first post in this series.

Blaine Carter user avatar by
Blaine Carter
·
Apr. 13, 16 · Database Zone · Tutorial
Like (4)
Save
Tweet
5.17K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we're going to take a look at the R in CRUD: Retrieve. We will be using the cx_Oracle driver to retrieve some data from the database tables, using the connection object created in the Initial Setup section of the first post in this series.

Simple Query

We will perform a simple query that pulls all of the records in no particular order. Here are the steps we'll follow in the code snippet below.

  1. Get a cursor object from our connection. We will use this cursor to perform our database operations.
  2. Prepare an SQL SELECT statement, specifying the columns desired from the table.
  3. Execute the statement.
  4. Fetch the results into a variable.
  5. Print the results.
# Query all rows
cur = con.cursor()
statement = 'select id, name, age, notes from cx_people'
cur.execute(statement)
res = cur.fetchall()
print (res)

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

Image title

[(1, 'Bob', 35, 'I like dogs'), (2, 'Kim', 27, 'I like birds')]

Extra Fun 1

Modify the statement to order by age. When you’re done, the results should be:

Image title

[(2, 'Kim', 27, 'I like birds'), (1, 'Bob', 35, 'I like dogs')]

Answer

cur = con.cursor()
statement = 'select id, name, age, notes from cx_people order by age'
cur.execute(statement)
res = cur.fetchall()
print (res)

Select Specific Rows

Now, suppose I only want to see the data for Kim. I want, therefore, to restrict the rows returned by the SELECT. This is done with a WHERE clause. There are several ways to do this. We could just put the where clause in the statement, and it would work.

statement = "select id, name, age, notes from cx_people where name = 'Kim'"

However, we want to choose the name at run time and store it in a variable called person_name. You could accept the value in as an argument or passed into a function, but we'll just set a variable to keep it simple.

person_name = 'Kim'

It is possible to simply concatenate the value into the statement.

statement = "select id, name, age, notes from cx_people where name= '" + person_name + "'"

This is very dangerous and opens our code to an SQL Injection attack. You can follow that link for more information, but we won't be going into detail in this series. Just know that you should, generally, never allow end user input to be fed directly into a dynamic SQL statement. A much safer way to pass external values into an SQL statement is by using bind variables with prepared statements. You have a couple of different options:

Positional

cur.execute('select id, name, age, notes from cx_people where name=:1 and age=:2',
 ('Bob', 35))

cur.execute('select id, name, age, notes from cx_people where name = :2 and age = :1',
 ('Bob', 35))

Notice the :1 and :2 are switched in the two examples. With a positional statement, the labels do not matter, it could just as well have been :1 and :something. What matters is the first :variable in the statement will be assigned the first of the provided values - 'Bob' and the second - 35.

Named

cur.execute('select id, name, age, notes from cx_people where name = :name and age = :age',
 {'name':'Bob', 'age':35})

cur.execute('select id, name, age, notes from cx_people where name = :name and age = :age',
 {'age':35, 'name':'Bob'})

With this method, the :name variable will be assigned the value of 'name' in the provided key value set. Notice, in both examples, that we do not wrap the bind variable for the name with quotes. This is handled automatically when the statement is prepared for execution.

Example

  1. Get a cursor object from our connection. We will use this cursor to perform our database operations.
  2. Assign 'Kim' to person_name
  3. Prepare an SQL statement using a bind variable
  4. Using the cursor, execute the query using the prepared statement.
  5. Fetch the results from the cursor into a variable.
  6. Print the results.
# Query for Kim
cur = con.cursor()
person_name = 'Kim'
statement = 'select id, name, age, notes from cx_people where name = :name'
cur.execute(statement, {'name':person_name})
res = cur.fetchall()
print (res)

This will return only the data for Kim:

Image title

[(2, 'Kim', 27, 'I like birds')]

Extra Fun 2

Modify the statement and variable to get the people older than 30.  When you're done, the results should be:

Image title

[(1, 'Bob', 35, 'I like dogs')]

Answer

cur = con.cursor()
person_age = 30
statement = 'select id, name, age, notes from cx_people where age > :age'
cur.execute(statement, {'age':person_age})
res = cur.fetchall()
print (res)

In this section, we took a look at some basic query functionality. When you experiment with more complex queries, if you run into problems, please leave a comment here or on Twitter, and we'll find an answer together.

Some Things You Could Try

  • Join the cx_people and cx_pets table to get the people and their pets.
  • Only retrieve the person's name and age.
  • Change the order to display in descending order.

Hint - If you have trouble getting a query to run in your code, try running it in SQL Plus or another database console tool. This will help determine if the problem is with the query or the code.

Series Sections

Initial Setup
Create records
Retrieve records
Update records
Delete records

Database SQL Plus

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 10 Steps to Become an Outstanding Java Developer
  • 6 Things Startups Can Do to Avoid Tech Debt
  • How to Generate Fake Test Data
  • Composable Architecture

Comments

Database Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo