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

那年仲夏 提交于 2019-12-08 23:58:40

问题


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

The problem is that sometimes it already exists. So previous to executing the query I need to check if the column already exists.

If it does, then I won't execute the query.

Is there a way in sqlite to do that? Or do I have to make it through a try-catch block in python code?

Thanks a lot in advance!


回答1:


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

PRAGMA table_info('table_name');

More details on the pragma commands are availabel at the sqlite web site




回答2:


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 constructing special case queries.

You can wrap the above code in a AddColumn(cursor, table, column) function so you can reuse it,
plus it'll make the code more readable.



来源:https://stackoverflow.com/questions/2354696/alter-table-sqlite-how-to-check-if-a-column-exists-before-alter-the-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!