From "Programming Python" by Mark Lutz:

curs.execute("Select * FROM people LIMIT 0")
colnames = [desc[0] for desc in curs.description]
Answer from Setjmp on Stack Overflow
🌐
PostgreSQL Wiki
wiki.postgresql.org › wiki › Using_psycopg2_with_PostgreSQL
Using psycopg2 with PostgreSQL - PostgreSQL wiki
# Note that even though we've returned the columns by name we can still # access columns by numeric index as well - which is really nice. cursor.execute('SHOW work_mem') # Call fetchone - which will fetch the first row returned from the # database. memory = cursor.fetchone() # access the column by numeric index: # even though we enabled columns by name I'm showing you this to # show that you can still access columns by index and iterate over them. print "Value: ", memory[0] # print the entire row print "Row: ", memory if __name__ == "__main__": main() If you have an extremely large result set
🌐
ZetCode
zetcode.com › python › psycopg2
Python PostgreSQL proramming with psycopg2 module
January 29, 2024 - Next we print all rows from the cars table with their column names. ... #!/usr/bin/python import psycopg2 con = psycopg2.connect(database='testdb', user='postgres', password='s$cret') with con: cur = con.cursor() cur.execute('SELECT * FROM cars') col_names = [cn[0] for cn in cur.description] rows = cur.fetchall() print(f'{col_names[0]} {col_names[1]} {col_names[2]}')
🌐
GeeksforGeeks
geeksforgeeks.org › get-column-name-and-column-type-with-python-psycopg2
Get Column name and Column type with Python psycopg2 | GeeksforGeeks
September 2, 2024 - Below code connects to the PostgreSQL database, retrieves column names and data types from the information_schema.columns for a specified table, and prints them. It then closes the cursor and database connection. ... import psycopg2 # Connect to your PostgreSQL database conn = psycopg2.connect( dbname="your_database_name", user="your_username", password="your_password", host="localhost", port="5432" ) # Create a cursor object cur = conn.cursor() # Create a table with various data types create_table_query = """ CREATE TABLE product ( product_id SERIAL PRIMARY KEY, product_name VARCHAR(255), price DECIMAL(10, 2), stock_quantity INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """ cur.execute(create_table_query) conn.commit() print("Table created successfully") # Close the cursor and connection cur.close() conn.close()
🌐
GeeksforGeeks
geeksforgeeks.org › get-column-names-from-postgresql-table-using-psycopg2
Get column names from PostgreSQL table using Psycopg2 | GeeksforGeeks
September 14, 2021 - This article is an illustration of how to extract column names from PostgreSQL table using psycopg2 and Python.
🌐
PYnative
pynative.com › home › python › databases › python select from postgresql table using psycopg2
Python Select from PostgreSQL Table using psycopg2
March 9, 2021 - ... Execute the select query using the cursor.execute() method. ... After successfully executing a Select operation, Use the fetchall() method of a cursor object to get all rows from a query result. it returns a list of rows.
Find elsewhere
🌐
Safe Community
community.safe.com › home › forums › fme form › authoring › generate list of column names from database table
Generate list of column names from database table | Community
October 18, 2017 - Execute the SELECT query using a cursor.execute() and use cursor.fetchall() to fetch the result. Iterate over the ResultSet using for loop to get all the columns. Close the cursor and database connection.
🌐
Hackers and Slackers
hackersandslackers.com › psycopg2-postgres-python
Psycopg2: PostgreSQL & Python the Old Fashioned Way
January 15, 2019 - These aren't lists of values, they're a new data structure unique to Psycopg2! While we see what appears to be a list of values, each value in each row has a key: the name of the column it belongs to. Check it out: def select_rows_dict_cursor(self, query): """Run SELECT query and return dictionaries.""" self.connect() with self.conn.cursor(cursor_factory=DictCursor) as cur: cur.execute(query) for row in cur.fetchall(): print(row['first_name']) Accessing values by column name ·
🌐
YouTube
youtube.com › fixitgeek
Python :How do I get a list of column names from a psycopg2 cursor?(5solution) - YouTube
Thanks For watching My video Please Like Share And Subscribe My Channel
Published   November 30, 2022
Views   3
🌐
sqlpey
sqlpey.com › python › top-8-methods-to-retrieve-column-names-using-psycopg2
Top 8 Methods to Retrieve Column Names Using Psycopg2 - …
November 1, 2024 - import psycopg2 DSN = "host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER" with psycopg2.connect(DSN) as connection: with connection.cursor() as cursor: cursor.execute("SELECT field1, field2 FROM table1") column_names = [desc[0] for desc in cursor.description] data_rows = cursor.fetchall() print("Column names: {}".format(column_names))
🌐
YouTube
youtube.com › how to fix your computer
PYTHON : How do I get a list of column names from a psycopg2 cursor? - YouTube
PYTHON : How do I get a list of column names from a psycopg2 cursor? [ Gift : Animated Search Engine : https://www.hows.tech/p/recommended.html ] PYTHON : H...
Published   December 6, 2021
Views   121
🌐
GitHub
gist.github.com › walkermatt › 061b61229a8614a5b871e7ac35b672da
python_psycopg2_postgis.md · GitHub
March 22, 2017 - import psycopg2 import psycopg2.extras # Create a connection to the database with psycopg2.connect("host=localhost dbname=postgis user=postgres password=postgres") as conn: # Create a regular cursor which will return a list of rows with each row # being a tuple of values in column order with conn.cursor() as cur: # Execute a query and return all rows as a list cur.execute("SELECT ogc_fid, name, st_asewkt(st_centroid(wkb_geometry)) as geom FROM county_region limit 10") rows = cur.fetchall() print print "# Rows as a list:" print print rows colnames = [desc.name for desc in cur.description] print
🌐
CSDN
devpress.csdn.net › python › 62fe077b7e66823466192fa5.html
Python psycopg2 postgres select columns including field names_python_Mangs-Python
August 18, 2022 - Hi I'd like to get a table from a database, but include the field names so I can use them from column headings in e.g. Pandas where I don't necessarily know all the field names in advance ... import psycopg2 as pq cn = pq.connect('dbname=mydb user=me') cr = cn.cursor() cr.execute('SELECT * FROM test1;') tmp = cr.fetchall() tmp
🌐
Dalibo
blog.dalibo.com › 2022 › 06 › 01 › psycopg-row-factories.html
How psycopg row factories help you write safer applications?
June 1, 2022 - @classmethod def from_row(cls, *, city: str, temp_lo: int, temp_hi: int, prcp: float, date: date) -> Weather: return cls( city=city, temperature=(temp_lo, temp_hi), precipitation=prcp, date=date ) @classmethod def row_factory(cls, cursor: Cursor[Any]) -> Callable[[Sequence[Any]], Weather]: columns = [column.name for column in cursor.description] def make_row(values: Sequence[Any]) -> Weather: row = dict(zip(columns, values)) return cls.from_row(**row) return make_row ... def get_weather_reports(conn: Connection[Any]) -> list[Weather]: with conn.cursor(row_factory=Weather.row_factory) as cur: cur.execute("SELECT * FROM weather") return cur.fetchall()
🌐
Itecnote
itecnote.com › tecnote › python-psycopg2-postgres-select-columns-including-field-names
Python psycopg2 postgres select columns including field ...
온라인 포커 추천 사이트 TOP10을 레이크백·보너스·입출금 기준으로 직접 비교했습니다. 최대 60% 레이크백부터 노디포짓 보너스까지, 2026 년 검증된 해외 포커 플랫폼만 정리했습니다.