当前位置: 动力学知识库 > 问答 > 编程问答 >

getting records from sqlite database with ruby

问题描述:

I have created a simple products table with sqlite database using ruby. I can retrieve the recors as per the normal select statement passing the product_code as a where condition.

anytime I retrieve a record I want to be able to store the record in an array and add to prices of the items selected to get the total value, just as in a online basket.

I am doing this in ruby without rails, just the console.

exsample of the select statement

def select(item_code)

item_code = item_code

begin

db = SQLite3::Database.new "test.db"

results = db.get_first_row "SELECT * FROM Products WHERE Product_code = ?",

item_code

puts results.join "\s"

rescue SQLite3::Exception => e

puts "Exception occured"

puts e

ensure

db.close if db

end

end

thank you.

网友答案:

Try something like this

$prices, $index_of_price = [], 0
#index_of_price is the index of the field in your result

def select(item_code) 
  begin 
    db = SQLite3::Database.new "test.db" 
    results = db.get_first_row "SELECT * FROM Products WHERE Product_code = ?", item_code 
    $prices << results[$index_of_price]
  rescue
    puts $!
  ensure 
   db.close if db
  end
end 

select 1
select 2

puts "Total is #{$prices.inject(0){|sum,item| sum + item}}"
分享给朋友:
您可能感兴趣的文章:
随机阅读: