1

私はrubyを使用してsqliteデータベースで簡単な製品テーブルを作成しました。product_codeをwhere条件として渡す通常のselectステートメントに従ってrecorsを取得できます。レコードを取得するときはいつでも、オンラインバスケットの場合と同様に、レコードを配列に格納し、選択したアイテムの価格に追加して合計値を取得できるようにしたいです。私はこれをレールのないルビーで、コンソールだけでやっています。selectステートメントの例

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

終わり

ありがとうございました。

4

1 に答える 1

0

このようなものを試してください

$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}}"
于 2012-08-10T15:02:50.660 に答える