ALTER TABLE Sqlite: how to check if a column exists before modifying a table?

I need to execute in python an SQL query that adds a new column in sqlite3.

The problem is that sometimes it already exists. Therefore, before executing the query, I need to check if the column exists.

If this happens, I will not fulfill the request.

Is there a way in sqlite for this? Or do I need to do this through a try-catch block in python code?

Thank you very much!

+6
python exists sqlite3 alter
Mar 01 '10 at 8:59
source share
2 answers

You can get a list of columns for a table using the following statement:

PRAGMA table_info('table_name'); 

More information on pragma commands is available at sqlite website

+12
Mar 01 '10 at 9:15
source share

IMO this

 conn = sqlite3.connect(':memory:') c = conn.cursor() try: c.execute('ALTER TABLE mytable ADD COLUMN newcolumn;') except: pass # handle the error c.close() 

is a better choice than creating special registry queries.

You can wrap the above code in the AddColumn function (cursor, column, column) so that you can reuse it,
plus this will make the code more readable.

+11
Mar 01 '10 at 9:30
source share



All Articles