Ich möchte eine allgemeine Möglichkeit, Spaltenbeschriftungen direkt aus den ausgewählten Spaltennamen zu generieren, und erinnern Sie sich daran, dass Python psycopg2 Modul diese Funktion unterstützt.Wie bekomme ich eine Liste von Spaltennamen von einem psycopg2 Cursor?
Antwort
Von "Programming Python" von Mark Lutz:
curs.execute("Select * FROM people")
colnames = [desc[0] for desc in curs.description]
Um erhalten die Spaltennamen in einer separaten Abfrage, können Sie die information_schema.columns Tabelle abfragen.
#!/usr/bin/env python3
import psycopg2
if __name__ == '__main__':
DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'
column_names = []
with psycopg2.connect(DSN) as connection:
with connection.cursor() as cursor:
cursor.execute("select column_name from information_schema.columns where table_schema = 'YOUR_SCHEMA_NAME' and table_name='YOUR_TABLE_NAME'")
column_names = [row[0] for row in cursor]
print("Column names: {}\n".format(column_names))
Um get Spaltennamen in der gleichen Abfrage als Datenzeilen, können Sie das Beschreibungsfeld des Cursors verwenden:
#!/usr/bin/env python3
import psycopg2
if __name__ == '__main__':
DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'
column_names = []
data_rows = []
with psycopg2.connect(DSN) as connection:
with connection.cursor() as cursor:
cursor.execute("select field1, field2, fieldn from table1")
column_names = [desc[0] for desc in cursor.description]
for row in cursor:
data_rows.append(row)
print("Column names: {}\n".format(column_names))
Ich habe bemerkt, dass Sie cursor.fetchone()
nach der Abfrage verwenden müssen holen Sie sich die Liste der Spalten in cursor.description
(dh in [desc[0] for desc in curs.description]
)
#!/usr/bin/python
import psycopg2
#note that we have to import the Psycopg2 extras library!
import psycopg2.extras
import sys
def main():
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
# print the connection string we will use to connect
print "Connecting to database\n ->%s" % (conn_string)
# get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string)
# conn.cursor will return a cursor object, you can use this query to perform queries
# note that in this example we pass a cursor_factory argument that will
# dictionary cursor so COLUMNS will be returned as a dictionary so we
# can access columns by their name instead of index.
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# tell postgres to use more work memory
work_mem = 2048
# by passing a tuple as the 2nd argument to the execution function our
# %s string variable will get replaced with the order of variables in
# the list. In this case there is only 1 variable.
# Note that in python you specify a tuple with one item in it by placing
# a comma after the first variable and surrounding it in parentheses.
cursor.execute('SET work_mem TO %s', (work_mem,))
# Then we get the work memory we just set -> we know we only want the
# first ROW so we call fetchone.
# then we use bracket access to get the FIRST value.
# 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()
I al so gewohnt, ähnliches Problem zu begegnen. Ich benutze einen einfachen Trick, um das zu lösen. Angenommen, Sie wie
in einer Liste Spaltennamen habencol_name = ['a', 'b', 'c']
Dann können Sie in 2,7
total_fields = len(cursor.description)
fields_names = [i[0] for i in cursor.description
Print fields_names
Nach der Ausführung Wenn Sie möchten, Um namedtuple obj von db query zu haben, können Sie das folgende Snippet verwenden:
from collections import namedtuple
def create_record(obj, fields):
''' given obj from db returns namedtuple with fields mapped to values '''
Record = namedtuple("Record", fields)
mappings = dict(zip(fields, obj))
return Record(**mappings)
cur.execute("Select * FROM people")
colnames = [desc[0] for desc in cur.description]
rows = cur.fetchall()
cur.close()
result = []
for row in rows:
result.append(create_record(row, colnames))
Diese allowes Sie Bestwerte zu bewerten, als ob sie Klasse Eigenschaften, dh
record.id, record.other_table_column_name usw.
oder noch kürzer
from psycopg2.extras import NamedTupleCursor
with cursor(cursor_factory=NamedTupleCursor) as cur:
cur.execute("Select * ...")
return cur.fetchall()
geschrieben SQL-Abfrage schreiben folgende Python-Skript, gehen Sie wie folgt
for row in cursor.fetchone():
print zip(col_name, row)
Eine andere Sache, die Sie tun können, ist, einen Cursor zu erstellen, mit dem Sie Ihre Spalten nach ihren Namen referenzieren können (das ist ein Bedürfnis, das mich zu dieser Seite geführt hat) der erste Platz):
import psycopg2
from psycopg2.extras import RealDictCursor
ps_conn = psycopg2.connect(...)
ps_cursor = psql_conn.cursor(cursor_factory=RealDictCursor)
ps_cursor.execute('select 1 as col_a, 2 as col_b')
my_record = ps_cursor.fetchone()
print (my_record['col_a'],my_record['col_b'])
>> 1, 2
- 1. Wie bekomme ich eine Liste von Spaltennamen auf sqlite3/iPhone?
- 2. Wie bekomme ich eine URL von einem Cursor-Objekt
- 3. psycopg2: Cursor bereits geschlossen
- 4. Python - Wie bekomme ich eine Liste von einem Cluster-Diagramm?
- 5. Wie bekomme ich eine Liste von CSVs in einem Ordner?
- 6. Wie wähle ich eine Liste von Tabellen aus einer anderen Liste mit einem Spaltennamen in R?
- 7. Ermitteln, ob von psycopg2 Cursor abrufen oder nicht?
- 8. Wie maskiert man das Objekt psycopg2 cursor?
- 9. Wie bekomme ich eine Liste von einer benutzerdefinierten Liste?
- 10. Wie bekomme ich eine Liste von Datentypen von View Columns?
- 11. Clojure: Wie bekomme ich eine Liste von Kombinationen von 'Koordinaten'?
- 12. Wie kann ich serverseitige Cursor mit Django und Psycopg2 verwenden?
- 13. Ich bekomme eine reine Liste von 'pyparsing.ParseResults'
- 14. Wie bekomme ich eine Liste von Kindtabellen für eine Datenbanktabelle?
- 15. Wie bekomme ich eine Liste von Objekten aus einer jlist
- 16. Wie bekomme ich eine Liste von CMS-Seiten in Magento?
- 17. Wie bekomme ich eine Unterliste von einer Liste in ocaml
- 18. Wie bekomme ich die Liste von Prozess
- 19. Wie bekomme ich den Cursor von Oracle mit Groovy?
- 20. JDBC - Wie bekomme ich den Spaltennamen (nicht den ursprünglichen Spaltennamen)
- 21. Wie verwende ich LoggingConnection von Psycopg2?
- 22. Wie bekomme ich eine Liste von Räumen, die von einem bestimmten Benutzer in xmpp verbunden sind?
- 23. Wie bekomme ich eine Liste von Routen von einem Modul/Verzeichnis in Laravel 5?
- 24. Wie bekomme ich eine Liste von laufenden Prozessnamen in VB.NET?
- 25. Wie bekomme ich eine Liste von Dokumenten in ArangoDB?
- 26. Wie bekomme ich eine Liste von Ländern und ihren Städten?
- 27. Wie bekomme ich eine Liste von Monaten Javascript
- 28. Wie bekomme ich eine Liste von Elementen mit Wattin?
- 29. Wie bekomme ich eine Liste von Benutzer/Profil vom Mitgliedschaftsanbieter?
- 30. Mediawiki Vorlagen: Wie bekomme ich eine Liste von Parameternamen?
Wenn Sie nur die Spaltennamen möchten, wählen Sie nicht alle Zeilen in der Tabelle. Dies ist effizienter: 'curs.execute (" SELECT * FROM people LIMIT 0 ")' – Demitri
Es lohnt sich, hinzuzufügen, dass dies sowohl für Views als auch für Tabellen funktioniert, während es nicht (einfach) möglich ist, Spaltennamen für Views zu erhalten 'informationsschema'. – wjv
Könnte intuitiver sein, den Namen als ein Attribut zu erhalten: colnames = [desc.name für desc in curs.description] – dexgecko