Search code examples
sqlrubysqlitesqlite3-ruby

Inserting SQLite rows via Ruby iteration


Inserting 5 rows of 4-column data into an existing SQLite db, and I get these errors...

/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>'

Here are last lines (59-61) from my .rb file:

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

Any suggestions?


Solution

  • You just have a small syntax error in your SQL. The column list for an INSERT should be comma delimited:

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

    so your Ruby should look like this:

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

    See the "column-name" loop in the SQLite INSERT syntax diagram:

    enter image description here