简体   繁体   English

用问号“?”代替SQL中的CREATE TABLE,DROP TABLE-限制

[英]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. 我是SQL的新手,正在研究如何编写干净/高效的SQL命令。

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. 我正在使用Python的sqlite3软件包,并且试图将问号替换与executemany()函数结合使用以编写高效的命令。

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? 我在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: 为了验证问题不在于executemany()函数,我尝试了:

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

and got a sqlite3.OperationalError: near "?": syntax error . 并得到了sqlite3.OperationalError: near "?": syntax error I'm thinking that ? 我在想吗? substitution may be limited to use only in the INSERT INTO and SELECT commands. 替换可能仅限于仅在INSERT INTOSELECT命令中使用。

The SQLite's statement DROP TABLE doesn't accept parameters in parentheses. SQLite的语句DROP TABLE不接受括号中的参数。 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语句定义为:

DROP TABLE定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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