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

写db.execute字符串必须有一种更干净的方法,否则我会挑剔吗?

最佳答案

除了在低氧的答案循环,也考虑使用变量插值:

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

请注意,您的entry元素最好都经过消毒,或者准备好迎接一个痛苦的世界,Bobby Tables风格。

关于ruby - 新手的 ruby 风格问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/861243/

10-11 04:16