Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3 and cursor.description

When using the sqlite3 module in python, all elements of cursor.description except the column names are set to None, so this tuple cannot be used to find the column types for a query result (unlike other DB-API compliant modules). Is the only way to get the types of the columns to use pragma table_info(table_name).fetchall() to get a description of the table, store it in memory, and then match the column names from cursor.description to that overall table description?

like image 590
astrofrog Avatar asked Oct 17 '09 22:10

astrofrog


People also ask

What is cursor () in Python?

It is an object that is used to make the connection for executing SQL queries. It acts as middleware between SQLite database connection and SQL query. It is created after giving connection to SQLite database.

What is sqlite3 used for?

A standalone command-line shell program called sqlite3 is provided in SQLite's distribution. It can be used to create a database, define tables, insert and change rows, run queries and manage an SQLite database file. It also serves as an example for writing applications that use the SQLite library.

Is SQLite and sqlite3 same?

The wiki tag description for both tags is the same: SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The sqlite3 has no synonyms but sqlite has sqlitedatabase as a solitary synonym.

What is cursor execute?

Description. This method executes a SQL query against the database. This is a DB API compliant call. Parameters are substituted using question marks, e.g. "SELECT name FROM table WHERE id=?". The parameter args is a tuple .


2 Answers

No, it's not the only way. Alternatively, you can also fetch one row, iterate over it, and inspect the individual column Python objects and types. Unless the value is None (in which case the SQL field is NULL), this should give you a fairly precise indication what the database column type was.

sqlite3 only uses sqlite3_column_decltype and sqlite3_column_type in one place, each, and neither are accessible to the Python application - so their is no "direct" way that you may have been looking for.

like image 128
Martin v. Löwis Avatar answered Oct 04 '22 20:10

Martin v. Löwis


I haven't tried this in Python, but you could try something like

SELECT *
FROM sqlite_master
WHERE type = 'table';

which contains the DDL CREATE statement used to create the table. By parsing the DDL you can get the column type info, such as it is. Remember that SQLITE is rather vague and unrestrictive when it comes to column data types.

like image 35
Michael Dillon Avatar answered Oct 04 '22 19:10

Michael Dillon