rubynewbie
rubynewbie

Reputation: 87

A question of ruby style from a newbie

USER = "user"
PASS = "pass"

QUERY = "SELECT c1, c2, c3, c4, c5, c6, c7 FROM table"

SQLITE_SCHEMA = 'c1, c2, c3, c4, c5, c6, c7'

sqlite_db = SQLite3::Database.new('sqlite.db')
odbc_db = DBI.connect('DBI:ODBC:database', USER, PASS)
odbc_db.select_all(QUERY) do |entry|
  sqlite_db.execute "insert into smnt (" + SQLITE_SCHEMA + ") values ('" + entry[0].to_s + "','" + 
                                                                           entry[1].to_s + "','" + 
                                                                           entry[2].to_s + "','" +
                                                                           entry[3].to_s + "','" +
                                                                           entry[4].to_s + "','" + 
                                                                           entry[5].to_s + "','" +
                                                                           entry[6].to_s + "')" 
  end

There must be a cleaner way to write the db.execute string, or am I being picky?

Upvotes: 1

Views: 124

Answers (3)

Toby Hede
Toby Hede

Reputation: 37143

How about:

" VALUES (#{entry.collect{|e|"'"+e.to_s+"'"}.join(",")})"

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223213

Apart from the loop in hypoxide's answer, also consider using variable interpolation:

sqlite_db.execute "insert into smnt (#{SQLITE_SCHEMA}) 
  values (#{entry.map {|e| "'#{e.to_s}'"}.join(',')})"

Note that your entry elements had better all be sanitised, or be prepared for a world of pain, Bobby Tables style.

Upvotes: 4

Daniel
Daniel

Reputation: 11064

You could write a for loop for the string... you'd save a few lines of code.

Upvotes: 1

Related Questions