How do I fetch column names from a db table into an array, using PostgreSQL and Ruby?

霸气de小男生 提交于 2019-12-25 00:27:35

问题


How can I iterate through all of the column headers in a table for a given database and add each column name individually to an array?

I know I can gather all of the information from the table using SELECT * FROM my_table but I need to work with just the column headers at this point. What is the best way to accomplish this?


回答1:


Are you using the pg gem? If so, you can try this:

require 'pg'

# `db_config` must contain your database configuration
conn = PG::Connection.open(db_config)

column_names = conn.query("SELECT * FROM my_table LIMIT 1").first.keys



回答2:


I recommend using

select column_name from information_schema.columns where table_name='my_table' 

as

SELECT * FROM my_table LIMIT 1 

will not return column names if the table is empty.

http://www.postgresql.org/message-id/AANLkTilsjTAXyN5DghR3M2U4c8w48UVxhov4-8igMpd1@mail.gmail.com



来源:https://stackoverflow.com/questions/26986443/how-do-i-fetch-column-names-from-a-db-table-into-an-array-using-postgresql-and

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!