0

我正在努力循环通过 Ruby 方法中的“INSERT INTO”sqlite 语句。请指教。我的代码如下所示。错误消息似乎表明 Ruby 无法识别方法中的 db 对象?抱歉有点菜鸟,但我已经在互联网上搜寻了,但我找不到答案:(

require "sqlite3"
require "nokogiri"

begin

db = SQLite3::Database.new('RM.db')
db.execute "CREATE TABLE IF NOT EXISTS Properties(address TEXT, askingPrice TEXT)"

def get_property_list(newpage, dbname)
    resultspage = Nokogiri::HTML(open(newpage))
    details = resultspage.css("div.details.clearfix")
    count_items = details.count
    puts "there are #{count_items} items on this page"

    for i in 0..count_items-1
        address = resultspage.css("span.displayaddress")[i]
        asking_price = resultspage.css("p.price")[i]

        puts address.text
        puts asking_price.text

        dbname.execute "INSERT INTO Properties VALUES(#{address}, #{asking_price})"

    end
end

get_property_list("someurl.com", db)

    rows = db.execute("select * from Properties")
    p rows

ensure
    db.close if db
end
4

1 回答 1

0

您没有在 INSERT 中引用任何一个值。您根本不应该对 SQL 使用字符串插值,使用绑定参数并始终指定列名:

dbname.execute 'INSERT INTO Properties (address, askingPrice) VALUES (?, ?)', address, asking_price

或者你可以准备一个声明并一遍又一遍地使用它:

insert = dbname.prepare('INSERT INTO Properties (address, askingPrice) VALUES (?, ?)')
for i in 0..count_items-1
  #...
  insert.execute(address, asking_price)
end
于 2013-01-18T01:33:26.437 回答