DZone
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
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Full-Stack Observability Essentials: Explore the fundamentals of system-wide observability and key components of the OpenTelemetry standard.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Create a CDC Event Stream From Oracle Database to Kafka With GoldenGate
  • A Better Web3 Experience: Account Abstraction From Flow (Part 2)
  • Training a Handwritten Digits Classifier in Pytorch With Apache Cassandra Database
  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications

Trending

  • Auditing Spring Boot Using JPA, Hibernate, and Spring Data JPA
  • How To Verify Database Connection From a Spring Boot Application
  • How To Optimize Feature Sets With Genetic Algorithms
  • GitHub Action Recipes: Building and Pushing Docker Images to a Container Registry
  1. DZone
  2. Data Engineering
  3. Databases
  4. Select (cRud) Using Ruby-OCI8

Select (cRud) Using Ruby-OCI8

In this post, we’re going to take a look at the R in CRUD: Retrieve. This article focuses on utilizing Ruby in your database to query and retrieve data.

Blaine Carter user avatar by
Blaine Carter
·
Sep. 25, 16 · Tutorial
Like (1)
Save
Tweet
Share
3.08K 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 ruby-oci8 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. Create the connection object. We will use this object to perform our database operations.
  2. Define the SQL SELECT statement, specifying the columns desired from the table.
  3. Create a cursor by parsing the statement.
  4. Execute the cursor.
  5. Fetch and loop through the rows.
  6. Print each row.
# Query all rows
con = OCI8.new(connectString)
statement = 'select id, name, age, notes from lcs_people'
cursor = con.parse(statement)
cursor.exec
cursor.fetch() {|row|
    print row
}

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


[#<BigDecimal:15bcb00,'0.1E1',9(18)>, "Bob", #<BigDecimal:15bc790,'0.35E2',9(18)>, "I like dogs"][#<BigDecimal:15bd1b8,'0.2E1',9(18)>, "Kim", #<BigDecimal:193bf60,'0.27E2',9(18)>, "I like birds"]

This is not real pretty, so from here on, we’ll use printf.

printf "Id: %d, Name: %s, Age: %d, Notes: %s\n", row[0], row[1], row[2], row[3]

Much better:

select1pretty



Id: 1, Name: Bob, Age: 35, Notes: I like dogs
Id: 2, Name: Kim, Age: 27, Notes: I like birds

Extra Fun 1

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


Id: 2, Name: Kim, Age: 27, Notes: I like birds
Id: 1, Name: Bob, Age: 35, Notes: I like dogs


Answer:

con = OCI8.new(connectString);

statement = 'select id, name, age, notes from lcs_people order by age'
cursor = con.parse(statement)
cursor.exec
cursor.fetch() {|row|
    printf "Id: %d, Name: %s, Age: %d, Notes: %s\n", row[0], row[1], row[2], row[3]
}

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 lcs_people where name = 'Kim'"

However, we want to choose the name at runtime and store it in a variable called person_name. You could accept the value in as an argument 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 lcs_people where name = '#{person_name}'"

This is very dangerous and opens our code to a 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 the SQL statement is by using bind variables with prepared statements.

You have a couple different options:

Positional

statement = "select id, name, age, notes from lcs_people where name = :1 and age = :2"
cursor = con.parse(statement)
cursor.bind_param(1, 'Bob')
cursor.bind_param(2, 35)

statement = "select id, name, age, notes from lcs_people where name = :2 and age = :1"
cursor = con.parse(statement)
cursor.bind_param(1, 'Bob')
cursor.bind_param(2, 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 value of the bind_param with the index of 1, the second the value of index 2 and so on.

Positional bind parameters will us an integer as the key in bind_param().

Named

statement = "select id, name, age, notes from lcs_people where name = :name and age = :age"
cursor = con.parse(statement)
cursor.bind_param('name', 'Bob')
cursor.bind_param('age', 35)

statement = "select id, name, age, notes from lcs_people where name = :age and age = :name"
cursor = con.parse(statement)
cursor.bind_param('age', 'Bob')
cursor.bind_param('name', 35)

With this method, the :name variable will be assigned the value of ‘name’ in the provided key value set.

In the second example, I switched the labels in the SQL, and I also had to switch the keys in the bind_parameter calls so the correct value is still used.

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. Create the connection object.
  2. Create the person_name variable and assign it a value of ‘Kim.’
  3. Define the SQL SELECT statement, specifying the columns desired from the table.
  4. Create a cursor by parsing the statement.
  5. Bind the value of person_name to :name.
  6. Execute the cursor.
  7. Fetch and loop through the rows.
  8. Print each row.
# Query for Kim
con = OCI8.new(connectString)

person_name = 'Kim'
statement = "select id, name, age, notes from lcs_people where name=:name"
cursor = con.parse(statement)
cursor.bind_param('name', person_name)
cursor.exec
cursor.fetch() {|row|
   printf "Id: %d, Name: %s, Age: %d, Notes: %s\n", row[0], row[1], row[2], row[3]
}

This will return only the data for Kim:


Id: 2, Name: Kim, Age: 27, Notes: 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:


Id: 1, Name: Bob, Age: 35, Notes: I like dogs


Answer:

con = OCI8.new(connectString)

statement = "select id, name, age, notes from lcs_people where age > :age"
cursor = con.parse(statement)
cursor.bind_param('age', 30)
cursor.exec
cursor.fetch() {|row|
    printf "Id: %d, Name: %s, Age: %d, Notes: %s\n", row[0], row[1], row[2], row[3]
}

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

Some things you could try

  • Join the lcs_people and lcs_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.

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.

Related

  • Create a CDC Event Stream From Oracle Database to Kafka With GoldenGate
  • A Better Web3 Experience: Account Abstraction From Flow (Part 2)
  • Training a Handwritten Digits Classifier in Pytorch With Apache Cassandra Database
  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: