Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Help w/ SQL statement to SQLite3 DB in Ruby 1.9.1

Posted on 2010-08-13
15
611 Views
Last Modified: 2012-06-21
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
0
Comment
Question by:FOS-Bret
  • 7
  • 7
15 Comments
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 33433993
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.
0
 
LVL 13

Expert Comment

by:darren-w-
ID: 33434033
Try placing the string values in speech marks

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


0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 33434065
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)
0
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 

Author Comment

by:FOS-Bret
ID: 33434278
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
   
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 33434348
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.
0
 

Author Comment

by:FOS-Bret
ID: 33434386
mwvisa1,
I'll try that on Monday as the system is at work and I'm done for the weekend.
Thanks,
Bret
0
 

Author Comment

by:FOS-Bret
ID: 33440886
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
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 33440907
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.
0
 

Author Comment

by:FOS-Bret
ID: 33440951
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

0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 33440988
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

0
 

Author Comment

by:FOS-Bret
ID: 33443142
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
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 33443170
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 ? ...
0
 

Author Comment

by:FOS-Bret
ID: 33448602
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
0
 

Accepted Solution

by:
FOS-Bret earned 0 total points
ID: 33459369
OK. I found the answer here:

http://www.eggheadcafe.com/software/aspnet/36149991/sqlite-placeholder-problem.aspx

Basically, you have to pass the variables in an array rather than one-by-one. So, the following line:

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

becomes:

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

It's working fine now. Thanks for the effort. I appreciate it.

-Bret
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 33460006
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
0

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In database programming, custom sort order seems to be necessary quite often, at least in my experience and time here at EE. Within the realm of custom sorting is the sorting of numbers and text independently (i.e., treating the numbers as number…
In Ruby, Call or invoke a API DLL library is easily via Win32API class, win32-api gem or other gems. For general DLL API call, there are quite a few references, some good tips list below: http://www.rubytips.org/2008/05/13/accessing-windows-api-fro…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question