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

Update (crUd) Using Ruby-OCI8

DZone's Guide to

Update (crUd) Using Ruby-OCI8

Learn how you can interact with your database using Ruby. In this case, we're examining the U in CRUD — updating your data.

· 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 U in CRUDUpdate.

We use the ruby-oci8 driver to update some data in the database tables, using the connection object created in the Initial Setup section of the first post in this series.

Note: Please review all example code and only run it if you are sure it will not cause any problems with your system.

Helper Function

My helper function get_all_rows() encapsulates a select statement used to verify that the updates 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')
 connectString = ENV['db_connect']
 con = OCI8.new(connectString)

 # Query all rows
 statement = 'select id, name, age, notes from lcs_people order by id';

 if data_type == 'pets'
 statement = 'select id, name, owner, type from lcs_pets order by owner, id'
 end

 cursor = con.parse(statement)
 cursor.exec
 printf " %s:\n", label
 cursor.fetch() {|row|
   if data_type == 'people'
     printf " Id: %d, Name: %s, Age: %d, Notes: %s\n", row[0], row[1], row[2], row[3]
   else
     printf " Id: %d, Name: %s, Owner: %d, Type: %s\n", row[0], row[1], row[2], row[3]
   end
 }
 printf "\n"
end

Add this function to the top of your file.

Resetting the Data

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

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

# Query all rows
require 'oci8'
connectString = ENV['db_connect']
con = OCI8.new(connectString)

# Delete rows
cursor = con.parse("delete from lcs_pets")
cursor.exec

# Reset Identity Coulmn
cursor = con.parse("alter table lcs_pets modify id generated BY DEFAULT as identity (START WITH 8)")
cursor.exec

# Delete rows
cursor = con.parse("delete from lcs_people")
cursor.exec

# Reset Identity Coulmn
cursor = con.parse("alter table lcs_people modify id generated BY DEFAULT as identity (START WITH 3)")
cursor.exec

# Insert default people rows
cursor = con.parse("INSERT INTO lcs_people(id, name, age, notes) VALUES (:id, :name, :age, :notes)")
cursor.max_array_size = 2
cursor.bind_param_array(:id, [1, 2])
cursor.bind_param_array(:name, ["Bob", "Kim"])
cursor.bind_param_array(:age, [35, 27])
cursor.bind_param_array(:notes, ["I like dogs", "I like birds"])
people_row_count = cursor.exec_array
printf " %d people rows inserted\n", people_row_count

# Insert default pet rows
cursor = con.parse("INSERT INTO lcs_pets(id, name, owner, type) VALUES (:id, :name, :owner, :type)")
cursor.max_array_size = 7
cursor.bind_param_array(:id, [1, 2, 3, 4, 5, 6, 7])
cursor.bind_param_array(:name, ["Duke", "Pepe", "Princess", "Polly", "Rollo", "Buster", "Fido"])
cursor.bind_param_array(:owner, [1, 2, 1, 1, 1, 1, 1])
cursor.bind_param_array(:type, ["dog", "bird", "snake", "bird", "horse", "dog", "cat"])
pet_row_count = cursor.exec_array
printf " %d pet rows inserted\n", pet_row_count

con.commit

Boilerplate Template

The template we will be using is:

require 'oci8'
connectString = ENV['db_connect']

def get_all_rows (label, data_type = 'people')
 connectString = ENV['db_connect']
 con = OCI8.new(connectString)

 # Query all rows
 statement = 'select id, name, age, notes from lcs_people order by id';

 if data_type == 'pets'
   statement = 'select id, name, owner, type from lcs_pets order by owner, id'
 end

 cursor = con.parse(statement)
 cursor.exec
 printf " %s:\n", label
 cursor.fetch() {|row|
   if data_type == 'people'
     printf " Id: %d, Name: %s, Age: %d, Notes: %s\n", row[0], row[1], row[2], row[3]
   else
     printf " Id: %d, Name: %s, Owner: %d, Type: %s\n", row[0], row[1], row[2], row[3]
   end
 }
 printf "\n"
end

con = OCI8.new(connectString)

get_all_rows('Original Data')

# Your code here

get_all_rows('New Data')

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

Simple Update

We will perform a simple update that modifies a single record in the lcs_people table.  These are the steps performed in the code snippet below.

  • Prepare a SQL UPDATE statement, changing age to 31 for the record with an id of 1.
  • Parse the statement to create a cursor.
  • Bind the age and id values.  (See the R part of this series for an explanation of bind variables.)
  • Execute the statement.
  • Commit the transaction.
statement = "update lcs_people set age = :age where id = :id"
cursor = con.parse(statement)
cursor.bind_param(:age,31)
cursor.bind_param(:id,1)
cursor.exec
con.commit

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

Image title

 Example: ruby update1.rb 
 Original Data:
 Id: 1, Name: Bob, Age: 35, Notes: I like dogs
 Id: 2, Name: Kim, Age: 27, Notes: I like birds

 New Data:
 Id: 1, Name: Bob, Age: 31, Notes: I like dogs
 Id: 2, Name: Kim, Age: 27, Notes: I like birds

Extra Fun 1

Update Bob's notes to 'I like cats' .

Your results should be:

Image title

 Original Data:
 Id: 1, Name: Bob, Age: 31, Notes: I like dogs
 Id: 2, Name: Kim, Age: 27, Notes: I like birds

 New Data:
 Id: 1, Name: Bob, Age: 31, Notes: I like cats
 Id: 2, Name: Kim, Age: 27, Notes: I like birds

Answer:

statement = "update lcs_people set notes = :notes where id = :id"
cursor = con.parse(statement)
cursor.bind_param(:notes,"I like cats")
cursor.bind_param(:id,1)
cursor.exec
con.commit

Reset the Data

Now is a good time to run reset_data.rb.

Boilerplate Change

Change the boilerplate get_all_rows statements to get pet data.

get_all_rows('Original Data', 'pets');

# Your code here

get_all_rows('New Data', 'pets');

Make Sure Your Where Clause Is Specific

In the above example, notice that we used the id column in our where clause.  For our data set, id is the primary key.  You do not always have to use a primary key, but you should make sure you only update the rows you intend to.

Next, let's look at updating multiple rows. We'll have Bob give his dog Duke to Kim.

  • Prepare a SQL UPDATE statement, changing owner to 2 for the record with an owner of 1 and a type of 'dog'.
  • Parse the statement to create a cursor.
  • Bind the newOwner, oldOwner and type values.
  • Execute the statement.
  • Commit the transaction.
statement = "update lcs_pets set owner = :newOwner where owner = :oldOwner and type = :type"
cursor = con.parse(statement)
cursor.bind_param(:newOwner,2)
cursor.bind_param(:oldOwner,1)
cursor.bind_param(:type,"dog")
cursor.exec
con.commit

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

Image title

 Original Data:
 Id: 1, Name: Duke, Owner: 1, Type: dog
 Id: 3, Name: Princess, Owner: 1, Type: snake
 Id: 4, Name: Polly, Owner: 1, Type: bird
 Id: 5, Name: Rollo, Owner: 1, Type: horse
 Id: 6, Name: Buster, Owner: 1, Type: dog
 Id: 7, Name: Fido, Owner: 1, Type: cat
 Id: 2, Name: Pepe, Owner: 2, Type: bird

 New Data:
 Id: 3, Name: Princess, Owner: 1, Type: snake
 Id: 4, Name: Polly, Owner: 1, Type: bird
 Id: 5, Name: Rollo, Owner: 1, Type: horse
 Id: 7, Name: Fido, Owner: 1, Type: cat
 Id: 1, Name: Duke, Owner: 2, Type: dog
 Id: 2, Name: Pepe, Owner: 2, Type: bird
 Id: 6, Name: Buster, Owner: 2, Type: dog

In our example we only used owner and type, assuming that Bob only had one dog, Duke, as it is in our original data.  With the new reset data function, we added a second dog, Buster.  This example is intended to demonstrate what may happen when multiple users are working with the same data set.

In our data, the only unique identifier for lcs_pets is id.  Bob may have two dogs, or even two dogs named Duke.  Make sure if you intend to change a specific row you use a unique identifier.

It also helps to...

Verify the Number of Affected Rows

Now let's give Buster back to Bob.  This time we will use the unique id column and we will print out the number of rows affected using the return value from cursor.exe.

  • Prepare a SQL UPDATE statement.
  • Parse the statement to create a cursor.
  • Bind the newOwner to 1 and id to 6.
  • Execute the statement returning the number of changed rows.
  • Commit the transaction.
  • Print the number of changed rows.
statement = "update lcs_pets set owner = :newOwner where id = :id"
cursor = con.parse(statement)
cursor.bind_param(:newOwner,2)
cursor.bind_param(:id,6)
changed = cursor.exec
con.commit

printf "Number of rows updated: %d\n\n", changed

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

Image title

 Original Data:
 Id: 3, Name: Princess, Owner: 1, Type: snake
 Id: 4, Name: Polly, Owner: 1, Type: bird
 Id: 5, Name: Rollo, Owner: 1, Type: horse
 Id: 7, Name: Fido, Owner: 1, Type: cat
 Id: 1, Name: Duke, Owner: 2, Type: dog
 Id: 2, Name: Pepe, Owner: 2, Type: bird
 Id: 6, Name: Buster, Owner: 2, Type: dog

Number of rows updated: 1

 New Data:
 Id: 3, Name: Princess, Owner: 1, Type: snake
 Id: 4, Name: Polly, Owner: 1, Type: bird
 Id: 5, Name: Rollo, Owner: 1, Type: horse
 Id: 7, Name: Fido, Owner: 1, Type: cat
 Id: 1, Name: Duke, Owner: 2, Type: dog
 Id: 2, Name: Pepe, Owner: 2, Type: bird
 Id: 6, Name: Buster, Owner: 2, Type: dog

Cursor.exe will return the number of rows affected for insert, update and delete statements and for a select statement, it returns the number of the select-list.

Extra Fun 2

Give all birds to Kim that she doesn't already have and print the number of affected rows .

Your results should be:

Image title

 Original Data:
 Id: 3, Name: Princess, Owner: 1, Type: snake
 Id: 4, Name: Polly, Owner: 1, Type: bird
 Id: 5, Name: Rollo, Owner: 1, Type: horse
 Id: 7, Name: Fido, Owner: 1, Type: cat
 Id: 1, Name: Duke, Owner: 2, Type: dog
 Id: 2, Name: Pepe, Owner: 2, Type: bird
 Id: 6, Name: Buster, Owner: 2, Type: dog

Number of rows updated: 1

 New Data:
 Id: 3, Name: Princess, Owner: 1, Type: snake
 Id: 5, Name: Rollo, Owner: 1, Type: horse
 Id: 7, Name: Fido, Owner: 1, Type: cat
 Id: 1, Name: Duke, Owner: 2, Type: dog
 Id: 2, Name: Pepe, Owner: 2, Type: bird
 Id: 4, Name: Polly, Owner: 2, Type: bird
 Id: 6, Name: Buster, Owner: 2, Type: dog

Answer:

statement = "update lcs_pets set owner = :newOwner where type = :type and owner != :oldOwner"
cursor = con.parse(statement)
cursor.bind_param(:newOwner,2)
cursor.bind_param(:type,"bird")
cursor.bind_param(:oldOwner,2)
changed = cursor.exec
con.commit

printf "Number of rows updated: %d\n\n", changed

Some Other Things You Could Try

  • Change multiple column values
  • Perform an update that changes all rows, if the row count is greater than 2, rollback the change

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:
ruby ,oracle ,crud ,database

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}