【问题标题】:Get column heading names from MySQL result in Ruby从 MySQL 结果获取 Ruby 中的列标题名称
【发布时间】:2010-01-12 22:56:05
【问题描述】:

我正在使用 Ruby mysql 模块。

我想打印查询结果并包含列名。我很难找到给我这些名称数组的方法。我的值如下所示。

result = my.query("select * from foo")

result.each 做 |row|将 row.join(',') 结束

感谢您的帮助!

【问题讨论】:

    标签: mysql ruby dbi


    【解决方案1】:
    
     result.fetch_fields.each_with_index do |info, i|
           printf "--- Column %d (%s) ---\n", i, info.name
           printf "table:            %s\n", info.table
           printf "def:              %s\n", info.def
           printf "type:             %s\n", info.type
           printf "length:           %s\n", info.length
           printf "max_length:       %s\n", info.max_length
           printf "flags:            %s\n", info.flags
           printf "decimals:         %s\n", info.decimals
         end
    

    【讨论】:

    【解决方案2】:

    这可能无法直接回答您的问题,但您可能会从查看数据库抽象层中受益。其中有几个用于 Ruby,最值得注意的是 ActiveRecord。 ActiveRecord 作为 Ruby on Rails 框架的模型部分捆绑在一起,但您可以“独立”使用它而无需 Rails 的其余部分。

    有了它(或类似的东西),您将能够更快速、更准确地创建应用程序,因为它提供了与您的数据库通信的宝贵工具——您将花费大量时间自行开发这些工具。如果您选择将数据库供应商从 MySQL 更改为其他产品(例如 PostgreSQL 或 Oracle),则无需重新编码。

    【讨论】:

      【解决方案3】:

      您要搜索的方法是Mysql2::Result#fields。例如:

      > result = ActiveRecord::Base.connection.execute('SELECT 1 as "first_column_name", 2 as "second_column_name"')
      => #<Mysql2::Result:0x0000559c8b9d8370...
      > result.fields
      => ["first_column_name", "second_column_name"]
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-25
        • 1970-01-01
        • 1970-01-01
        • 2013-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多