ALTER TABLE Sqlite:如何在修改表之前检查列是否存在?
我需要在Python中执行一个SQL查询,用于在sqlite3中添加一个新列。
问题是,有时候这个列可能已经存在。所以在执行查询之前,我需要先检查一下这个列是否已经存在。
如果存在的话,我就不执行这个查询。
在sqlite中有没有办法做到这一点?还是说我必须通过Python代码中的try-catch块来处理?
非常感谢!
3 个回答
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))
16
在我看来,这段代码
conn = sqlite3.connect(':memory:')
c = conn.cursor()
try:
c.execute('ALTER TABLE mytable ADD COLUMN newcolumn;')
except:
pass # handle the error
c.close()
比写一些特殊情况的查询要好。
你可以把上面的代码放进一个叫做 AddColumn(cursor, table, column) 的函数里,这样就可以重复使用了,
而且这样也能让代码更容易理解。
16