Create temp table in SQLite if another table exists

前端 未结 1 1750
后悔当初
后悔当初 2021-01-26 06:18

I need to create a temp table (which is a copy of Employees table) in a SQLite database, provided the table by the name of \'Employees\' exists. There are only 2 columns in Empl

相关标签:
1条回答
  • 2021-01-26 06:48

    SQLite has almost no control logic; as an embedded database, it is designed to be used together with a 'real' programming language.

    You could just try to copy the data, and ignore the errors:

    try:
        c.execute("CREATE TEMP TABLE tempEmployees AS SELECT * FROM Employees")
    except:
        pass
    

    However, this would also suppress any other errors.

    A better idea is to check explicitly whether the table exists:

    c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Employees'")
    if c.fetchone():
        c.execute("CREATE TEMP TABLE tempEmployees AS SELECT * FROM Employees")
    
    0 讨论(0)
提交回复
热议问题