问题
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