通过Ruby迭代插入SQLite行

时间:2013-10-07 02:34:51

标签: sql ruby sqlite sqlite3-ruby

将5行4列数据插入现有的SQLite数据库,我收到这些错误......

/Users/Sam/.rvm/gems/ruby-2.0.0-p247/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `initialize': near "tagline": syntax error (SQLite3::SQLException)
        from /Users/Sam/.rvm/gems/ruby-2.0.0-p247/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `new'
        from /Users/Sam/.rvm/gems/ruby-2.0.0-p247/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `prepare'
        from /Users/Sam/.rvm/gems/ruby-2.0.0-p247/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:134:in `execute'
        from insert_code_sam.rb:60:in `block in <main>'
        from insert_code_sam.rb:59:in `times'
        from insert_code_sam.rb:59:in `<main>'

以下是我的.rb文件中的最后一行(59-61):

    5.times do
      db.execute('INSERT INTO index1 (name tagline blurb photo_url) 
        VALUES (?, ?, ?, ?)', ["name", "tagline", "blurb", "photo"])
    end

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

您的SQL中只有一个小的语法错误。 INSERT的列列表应以逗号分隔:

INSERT INTO index1 (name, tagline, blurb, photo_url) ...
                        ^        ^      ^

所以你的Ruby应该是这样的:

5.times do
  db.execute('INSERT INTO index1 (name, tagline, blurb, photo_url) VALUES (?, ?, ?, ?)', ["name", "tagline", "blurb", "photo"])
end

请参阅SQLite INSERT syntax图表中的“column-name”循环:

enter image description here