ProgrammingError 1064 doing CREATE TABLE AS SELECT from an existing table with MySQL in Python

ProgrammingError 1064 doing CREATE TABLE AS SELECT from an existing table with MySQL in Python

我在云端有一个现有的 table,我想复制它。我通过 pymysql 连接到我的数据库,从新用户提供的输入中提取用户名,我想创建一个新的 table 将由用户名调用,并且 table 将是一个原件的副本。当我 运行 下面的代码时,出现以下错误:

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''username' AS SELECT * FROM original_table' at line 1")

uname = blabla@bla.com
conn = pymysql.connect(
                    host="db.host",
                    port=int(3306),
                    user=user,
                    passwd=password,
                    db=db,
                    charset='utf8mb4'
                )
                cur = conn.cursor()
                table_name = uname.replace('@', '_').replace('.', '_')
                print('TABLE NAME:', table_name)
                cur.execute(""" CREATE TABLE %s AS SELECT * FROM original_table """, (table_name))

参数引用是为了引用。引用 table 名称不起作用,因为在 MySQL 中引用 table 名称的方式是使用反引号 (`),而不是引号。

MariaDB [test]>  CREATE TABLE 'username' AS SELECT * FROM my_table;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''username' AS SELECT * FROM my_table' at line 1

在这种情况下,您需要使用字符串格式来创建 SQL 语句(您可以使用反引号来防御 SQL-injection*) :

cur.execute(""" CREATE TABLE `%s` AS SELECT * FROM original_table """ % table_name)

* 我不是 SQL 注入方面的专家,所以如果 table_name 源自您的应用程序之外,请做一些研究。