如何在Ruby Sequel任意sql运行中找到列名

时间:2014-01-06 20:00:03

标签: ruby sequel

我使用Ruby Sequel DB.run运行任意sql。我想找出数据集的列名。

Ruby Sequel有可能吗?

2 个答案:

答案 0 :(得分:3)

你能提供一个最小的工作示例(一个代码示例,看你想要什么,如果可能的话)?

我猜你在做什么:

require 'sequel'

db = Sequel.sqlite()
db.create_table(:test){
  field :x1
  field :x2
}
db[:test].insert(1,2)
p db.run('select * from test') #->nil

如果您不使用run[],则会得到另一个结果:

p db['select * from test']  #-> #<Sequel::SQLite::Dataset: "select * from test">

根据此解决方案,您可以使用columns获取字段:

p db['select * from test'].columns  #->[:x1, :x2]
p db['select x1 from test'].columns  #->[:x1]

答案 1 :(得分:2)

使用续集的basic statup-up example

require "sequel"

# connect to an in-memory database
DB = Sequel.sqlite

# create an items table
DB.create_table :items do
  primary_key :id
  String :name
  Float :price
end

# create a dataset from the items table
items = DB[:items]

columns方法将返回为特定表定义的字段:

items.columns # => [:id, :name, :price]

您也可以直接使用:

DB[:items].columns # => [:id, :name, :price]