简体   繁体   中英

Question mark “?” substitution for CREATE TABLE, DROP TABLE in SQL - Limitations

I'm new to SQL and working on figuring out how to write clean/efficient SQL commands.

I'm using the sqlite3 package from Python, and I'm trying to use question mark substitution combined with the executemany() function to write efficient commands.

I've seen examples like this:

with sql.connect("db_file.db") as conn:
    cur = conn.cursor()
    purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
                ]
    cur.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
    conn.close()

And I'm wondering if I can use similar syntax for creating/dropping tables:

with sql.connect("db_file.db") as conn:
    cur = conn.cursor()
    tables = ["MajorInfo",
                "CourseInfo",
                "StudentInfo",
                "StudentGrades"]
    cur.executemany("DROP TABLE IF EXISTS (?);", tables)
    conn.close()

The code above throws the following exception:

Traceback (most recent call last):
  File "sql_test.py", line 4, in <module>
    sql1.student_db()
  File "/acmeshare/jastern/byu_vol2/SQL1/sql1.py", line 57, in student_db
    cur.executemany("DROP TABLE IF EXISTS (?);", tables)
  sqlite3.OperationalError: near "(": syntax error

Is what I am attempting possible in SQL? Is there a conventional way to do what I am attempting? Thanks!

Update:

To verify that the issue was not with the executemany() function, I tried:

table = "MajorInfo"
cur.execute("DROP TABLE IF EXISTS ?;", table)
conn.close()

and got a sqlite3.OperationalError: near "?": syntax error . I'm thinking that ? substitution may be limited to use only in the INSERT INTO and SELECT commands.

The SQLite's statement DROP TABLE doesn't accept parameters in parentheses. Also, it doesn't accept multiple parameters so what you want is most likely not possible, unfortunately.

The DROP TABLE statement is defined as:

DROP TABLE定义

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM