【问题标题】:ALTER TABLE Sqlite: how to check if a column exists before alter the table?ALTER TABLE Sqlite:如何在更改表之前检查列是否存在?
【发布时间】:2011-01-22 05:15:57
【问题描述】:

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

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

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

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

提前非常感谢!

【问题讨论】:

    标签: python sqlite exists alter


    【解决方案1】:

    无论出于何种原因,您想要一种明确的方法来检查列是否已经存在,您可以在下面找到完整的 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))
    

    【讨论】:

      【解决方案2】:

      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(cursor, table, column) 函数中,以便您可以重复使用它,
      此外,它会使代码更具可读性。

      【讨论】:

        【解决方案3】:

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

        PRAGMA table_info('table_name');
        

        有关编译指示命令的更多详细信息,请访问the sqlite web site

        【讨论】:

        • 问题被标记为“python”,但这并没有告诉您如何在 Python 中执行此操作
        猜你喜欢
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        • 2012-04-15
        • 2012-05-05
        • 1970-01-01
        • 2019-12-23
        • 2022-01-21
        相关资源
        最近更新 更多