Link to home
Start Free TrialLog in
Avatar of FOS-Bret
FOS-BretFlag for United States of America

asked on

Help w/ SQL statement to SQLite3 DB in Ruby 1.9.1

Hey All,

I'm a total Ruby beginner and nearly an SQL beginner. I'm working on exercises from the book "Beginning Ruby - From Novice to Professional."

The current exercise is a simple little CRUD app, connecting to an SQLite3 db. Here's a line that's giving me trouble:

$db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", job, name, gender, age) 

Open in new window


When this line executes, it always makes the first value (name, in this case) nil. I've swapped 'name' and 'job' (in both places) and then 'job' comes out nil when I display all records with "SELECT * FROM..."

Can anyone tell me what I'm doing wrong and why it's not taking the first parameter?

Thanks,
Bret
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Maybe there is a type conversion issue or other problem in structure of table as that appears to be the valid Ruby command afaik. Please post the create statement for the table.
Try placing the string values in speech marks

$db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)",' job, name, gender', age)


I figured those for variables and not literals, since the format string (parameterized string) approach was being used. If those are indeed string literals then you should include proper quoting. For Ruby it appears that is " from what I have seen so:

$db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", "job", "name", "gender", "age")

Or more appropriate to data types:
$db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", "a job", "john doe", "male", 50)
Avatar of FOS-Bret

ASKER

Sorry. I didn't make it clear before.

job, name, gender, and age are variables that get set before that statement with gets statements.

For example:

job = gets.chunk
name = gets.chunk
gender = gets.chunk
age = gets.chunk

Age gets put into the DB like...

age.to_i

The others just get put in as strings.

Anyway, if I put quotes around job, name, gender, and age, wouldn't that put those literal strings in instead of the values contained in those variables?

Thanks,
Bret
   
Correct. Only do that if passing literals. Have you tried that by the way? Can you try inserting a row directly in SQLite also and see what happens.
mwvisa1,
I'll try that on Monday as the system is at work and I'm done for the weekend.
Thanks,
Bret
Hey All,

I was able to RC into my work computer today to try the suggestions.

It's not the variables, because using literals instead produces the same result. Here's the code for the create_table and add_person methods. For the test in add_person, I commented out the original $db.execute line and added the one w/ the literals.

[code]
def create_table
  puts "Creating people table"
 
  $db.execute %q{
  CREATE TABLE people (
  id integer primary key,
  name varchar(50),
  job varchar(50),
  gender varchar(6),
  age integer)
  }
end

def add_person
  puts "Enter Name: "
  name = gets.chomp
  puts "Enter Job: "
  job = gets.chomp
  puts "Enter Gender: "
  gender = gets.chomp
  puts "Enter Age: "
  age = gets.chomp
  puts "Name: #{name}"
  # $db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", job, name, gender, age)
  $db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", "Male Escort", "Fred Garvin", "Male", 42)
end
[/code]

Thanks,
Bret
Have you checked that the table is actually created in SQLite, since it appears you are doing this via the Ruby code also? Note that if the table already exists with wrong structure, this statement will fail. You would need to drop the original table and recreate ; however, that is typically not what is desired as that would remove original data, so I would suggest moving this portion from your code and doing once directly in SQLite or put "delete table if exists people;" before the create table bit.

After you check on the table in SQLite, try running a regular insert statement from command line and ensure that is functioning.
Thanks. I've been deleting the file called "dbfile" each time before I run the code just in case, so I know it's gone. I put a puts statement at the beginning for debugging, and when I delete the db file, the app fails because I always forget to comment out that line. So, I know the table is being recreated each time.

Here's the entire program.

Thanks,
Bret

======


require 'rubygems'
require 'sqlite3'
$db = SQLite3::Database.new("dbfile")
$db.results_as_hash = true

def disconnect_and_quit
  $db.close
  puts "Bye."
  exit
end

def create_table
  puts "Creating people table"
  
  $db.execute %q{
  CREATE TABLE people (
  id integer primary key,
  name varchar(50),
  job varchar(50),
  gender varchar(6),
  age integer)
  }
end

def add_person
  puts "Enter Name: "
  name = gets.chomp
  puts "Enter Job: "
  job = gets.chomp
  puts "Enter Gender: "
  gender = gets.chomp
  puts "Enter Age: "
  age = gets.chomp
  puts "Name: #{name}"
  # $db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", job, name, gender, age)
  $db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", "Male Escort", "Fred Garvin", "Male", 42)
end

def find_person
  puts "Enter name or ID of person to find: "
  id = gets.chomp
  person = $db.execute("SELECT * FROM people WHERE name = ? OR id = ?", id, id.to_i).first
  unless person
    puts "No result found."
    return
  end
  puts %Q{Name: #{person['name']}
  Job: #{person['job']}
  Gender: #{person['gender']}
  Age: #{person['age']}}
end
 puts $db.execute("SELECT * FROM people")
loop do
  puts %q{Please select an option:

  1. Create people table.
  2. Add a person.
  3. Look for a person.
  4. Quit.}

  case gets.chomp
  when '1'
    create_table
  when '2'
    add_person
  when '3'
    find_person
  when '4'
    disconnect_and_quit
  end
end

Open in new window

Have a theory, try this:
require 'rubygems'
require 'sqlite3'
$db = SQLite3::Database.new("dbfile")
$db.results_as_hash = true

def disconnect_and_quit
  $db.close
  puts "Bye."
  exit
end

def create_table
  puts "Creating people table"
  
  $db.execute %q{
  CREATE TABLE people (
  id integer primary key autoincrement,
  name varchar(50),
  job varchar(50),
  gender varchar(6),
  age integer)
  }
end

def add_person
  puts "Enter Name: "
  name = gets.chomp
  puts "Enter Job: "
  job = gets.chomp
  puts "Enter Gender: "
  gender = gets.chomp
  puts "Enter Age: "
  age = gets.chomp
  puts "Name: #{name}"
  # $db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", job, name, gender, age)
  $db.execute("INSERT INTO people (job, name, gender, age) VALUES (?,?,?,?)", "Male Escort", "Fred Garvin", "Male", 42)
end

def find_person
  puts "Enter name or ID of person to find: "
  id = gets.chomp
  person = $db.execute("SELECT * FROM people WHERE name = ? OR id = ?", id, id.to_i).first
  unless person
    puts "No result found."
    return
  end
  puts %Q{Name: #{person['name']}
  Job: #{person['job']}
  Gender: #{person['gender']}
  Age: #{person['age']}}
end
 puts $db.execute("SELECT * FROM people")
loop do
  puts %q{Please select an option:

  1. Create people table.
  2. Add a person.
  3. Look for a person.
  4. Quit.}

  case gets.chomp
  when '1'
    create_table
  when '2'
    add_person
  when '3'
    find_person
  when '4'
    disconnect_and_quit
  end
end

Open in new window

Sorry. No luck.

I figured out that I could pass info for ALL columns (including the "id" column by specifying "nil" for that column value and letting Ruby (or SQLite3) fill in the autonumber. For example:

$db.execute( "INSERT INTO people values ( ?, ?, ?, ?, ? )", nil, name, job, gender, age )

That worked, but the point of the exercise is that you don't have to specify ALL column names. So I should be able to do something like the original line of code, but for some reason it accepts all values except the first and makes that one a nil.

I'm still dumbfounded.

Thanks,
Bret
Yeah, it doesn't make sense. My theory was that you were originally creating the id column without the autoincrement keyword but specified as primary key I was wondering if it was requiring that column be non-null and therefore causing your first column to be null somehow (though that still didn't make sense to me it was worth the try) ...

Not as good with Ruby, so do you know if this is valid?

$db.execute( "INSERT INTO people(job, name, gender, age) values ( '?', '?', '?', ? )", name, job, gender, age )

Or will it read that as literal ? ...
Hey,

Yeah, it bombed w/ the statement as is, but it took them as literals when I removed the variables on the end. Kicking points up to 500.

Thanks,
Bret
ASKER CERTIFIED SOLUTION
Avatar of FOS-Bret
FOS-Bret
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Glad you found that and thanks for posting for others in the Ruby community. My skill set is on the database side, so I wouldn't have probably made that connection, so I am glad to have learned something new myself. :)

Thanks!

Best regards,
Kevin