Search notes:

Python: sqlite3 - Cursor

description

The description property of a Cursor object allows to query the number of columns and their names from the most recently executed statement:
import sqlite3

db  = sqlite3.connect(':memory:')
cur = db.cursor()

db.execute("create table t (c1, c2, c3)")
db.execute("insert into t values('foo', 1, 'one'  )")
db.execute("insert into t values('bar', 2, 'two'  )")
db.execute("insert into t values('baz', 3, 'three')")

colWidth = 6

first = True
for rec in cur.execute('select * from t'):
    if first:
       for colName in [colDesc[0] for colDesc in cur.description]:
           print(' ', end='')
           print(colName.ljust(colWidth, ' '), end='')

       print('')

       for colNo in range(len(cur.description)):
           print(' ', end='')
           print('-'.ljust(colWidth, '-'), end='')

       print('')

       first = False

    for colNo in range(len(cur.description)):
        print(' ', end='')
        print(str(rec[colNo]).ljust(colWidth, ' '), end='')

    print('')
Github repository about-python, path: /standard-library/sqlite3/Cursor/description.py
This example prints:
 c1     c2     c3
 ------ ------ ------
 foo    1      one
 bar    2      two
 baz    3      three

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1759406537, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/standard-library/sqlite3/Cursor/index(77): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78