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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2354696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:25:54  来源:igfitidea点击:

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

pythonsqliteexistsalter

提问by Esabe

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

我需要在 python 中执行一个 SQL 查询,在 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?

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

Thanks a lot in advance!

非常感谢!

回答by My Other Me

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

有关 pragma 命令的更多详细信息,请访问sqlite 网站

回答by Nick Dandoulakis

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 casequeries.

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

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.

您可以将上述代码包装在 AddColumn(cursor, table, column) 函数中,以便您可以重用它,
而且它会使代码更具可读性。