Note that there are some explanatory texts on larger screens.

plurals
  1. POGet list of column names from an empty table
    primarykey
    data
    text
    <p>I'm using Python's <code>sqlite3</code> module and would like to get a list of all columns in a table when the table doesn't have any rows.</p> <p>Normally, if I create a database like</p> <pre><code>import sqlite3 conn = sqlite3.connect(":memory:") c = conn.cursor() # create the table schema c.execute('''create table stocks (date text, trans text, symbol text, qty real, price real)''') conn.commit() c.close() </code></pre> <p>Then I can get the column names with something like</p> <pre><code>conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('select * from stocks') r = c.fetchone() print r.keys() </code></pre> <p>The problem is, if the table is initially empty, <code>c.fetchone()</code> returns <code>None</code>. If there are rows committed, then I am able to get a list of the column names.</p> <p>Is there another way to do it? I went through the official <code>sqlite3</code> <a href="http://docs.python.org/library/sqlite3.html">module documentation</a>, but couldn't find anything useful in that regard.</p> <p>I guess I could put some dummy data in the table, then retrieve the column names and then delete the row, but I was hoping there's a more elegant way to do it.</p> <p><strong>Edit:</strong></p> <p>Seems there are a few ways to do it:</p> <ol> <li><p>Get the SQL that was used to create the table:</p> <pre><code>c.execute("""SELECT sql FROM sqlite_master WHERE tbl_name = 'stocks' AND type = 'table'""") </code></pre></li> <li><p>Use the <code>PRAGMA</code> statement from sqlite3:</p> <pre><code>c.execute("PRAGMA table_info(stocks)") </code></pre></li> <li><p>Use the <code>.description</code> field of the <code>Cursor</code> object</p> <pre><code>c.execute('select * from stocks') r=c.fetchone() print c.description </code></pre></li> </ol> <p>Of these, No.2 seems the simplest and most straight-forward. Thanks all for the help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload