ALTER TABLE Sqlite:如何在更改表之前检查列是否存在?

时间:2010-03-01 08:59:29

标签: python sqlite exists alter

我需要在python中执行一个SQL查询,在sqlite3中添加一个新列。

问题是有时它已经存在。因此,在执行查询之前,我需要检查列是否已存在。

如果是,那么我将不执行查询。

sqlite有办法做到这一点吗?或者我是否必须通过python代码中的try-catch块来实现它?

提前多多感谢!

3 个答案:

答案 0 :(得分:13)

您可以通过以下语句获取表的列列表:

PRAGMA table_info('table_name');

有关pragma命令的更多详细信息,请参见the sqlite web site

答案 1 :(得分:13)

IMO这个

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

是构建特殊情况查询的更好选择。

您可以将上述代码包装在AddColumn(游标,表格,列)功能中,以便重复使用, 加上它会使代码更具可读性。

答案 2 :(得分:0)

由于任何原因,您都想使用一种明确的方法来检查某列是否已存在,可以在下面找到完整的Python食谱。由您决定将代码包装到函数中还是对其进行改进

import sqlite3

sqlite_db = 'my_sqlite_db.sqlite'
col_to_test = 'my_column'
table_to_test = 'my_table_name'

con = sqlite3.connect(sqlite_db)
check_sqlite_col_exist_query = """SELECT count(*) > 0
FROM pragma_table_info('{}')
WHERE name=?;""".format

with con:
    q = con.execute(check_sqlite_col_exist_query(table_to_test), (col_to_test, ))
    col_exist = q.fetchone()
    col_exist = col_exist[0] > 0
    if not col_exist:
        print('"{}" column does not exist in table "{}"!'.format(col_to_test, table_to_test))
        # Do stuff here like adding your column or something else
    else:
        print('"{}" column already exist in table "{}"!'.format(col_to_test, table_to_test))
相关问题