使用动态生成的字段创建Sqlite表

时间:2017-01-25 03:16:07

标签: ruby sqlite

我在ruby中使用了sqlite3 gem,这里是gems github给出的例子:

require "sqlite3"

# Open a database
db = SQLite3::Database.new "test.db"

# Create a table
rows = db.execute <<-SQL
  create table numbers (
    name varchar(30),
    val int
  );
SQL

这是我的实现,我尝试用动态生成的字符串

替换db.execute的参数
require "sqlite3"

db_params = {
    db_name: "house-reps", 
    tables: 
        [
            {
                table_name: "house-reps-party",
                table_fields: [
                    "region varchar(30)",
                    "congress int",
                    "year int",
                    "party varchar(30)",
                    "percent int",
                    "seats int"
                ]
            }
        ]
}
def init_db(db_params)
    tables = db_params[:tables]

    db = SQLite3::Database.new "#{db_params[:db_name]}"
    tables.each do |table|
        db.execute("<<-SQL\n  create table #{table[:table_name]} (\n   #{table[:table_fields].join(",\n    ")}\n   );\nSQL")
    end
end

init_db(db_params)

以下是字符串插值的输出:

<<-SQL
  create table party-total (
   region varchar(30),
    congress int,
    year int,
    party varchar(30),
    percent int,
    seats int
   );
SQL

但是当我运行该程序时,它给了我这个:

/usr/local/lib/ruby/gems/2.4.0/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:91:in `initialize': near "<<": syntax error (SQLite3::SQLException)
    from /usr/local/lib/ruby/gems/2.4.0/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:91:in `new'
    from /usr/local/lib/ruby/gems/2.4.0/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:91:in `prepare'
    from /usr/local/lib/ruby/gems/2.4.0/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:137:in `execute'
    from database.rb:25:in `block in init_db'
    from database.rb:23:in `each'
    from database.rb:23:in `init_db'
    from database.rb:29:in `<main>'

我猜测它与db.execute的调用方式有关。我已经尝试过这些方法:

db.execute("<<-SQL\n  create table #{table[:table_name]} (\n   #{table[:table_fields].join(",\n    ")}\n   );\nSQL")

db.execute "<<-SQL\n  create table #{table[:table_name]} (\n   #{table[:table_fields].join(",\n    ")}\n   );\nSQL"

db.execute <<-SQL "\n  create table #{table[:table_name]} (\n   #{table[:table_fields].join(",\n    ")}\n   );\n" SQL

1 个答案:

答案 0 :(得分:1)

只需删除

即可
<<-SQL
SQL

这些不是字符串的一部分,而是多行字符串的“引号”。

这两个字符串都包含内容hello

"hello"

<<-SQL
hello
SQL