使用 mysql python 连接器动态创建表和列

creating Tables and columns dynamically using mysql python connector

我想使用 python 列表创建一个包含动态列的 table。列名在列表中,我想在 MySQL 查询中引用它们。我正在使用 MySQL.connector 和 python 3.4.3.

下面是我试过的代码:

col names:  ['Last Name', 'First Name', 'Job', 'Country']
table_name = 'stud_data'
query = "CREATE TABLE IF NOT EXISTS"+table_name+"("+"VARCHAR(250),".join
(col) + "Varchar(250))"
print("Query is:" ,query)
cursor.execute(query)
conn.commit()

但我收到以下错误:

mysql.connector.errors.ProgrammingError: 1064 (42000): 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 'Name VARCHAR(250),First Name VARCHAR(250),Job VARCHAR(250),Country VARCHAR(250))' at line 1

查询如下所示:

Query is: CREATE TABLE IF NOT EXISTS stud_data (Last Name VARCHAR(250),First Name VARCHAR(250),Job VARCHAR(250),Country VARCHAR(250))

请帮忙解决这个问题。提前致谢

列名中有空格。 即 'First Name' 而不是 'FirstName',删除空格将解决您的问题。 如果要保留空格,请使用反引号 '`' 将字符串换行

示例代码:

columns = [ ('Last Name', 'First Name', 'Job', 'Country') ] #list of tuples

for p in columns:
    q = """ CREATE TABLE IF NOT EXISTS stud_data (`{col1}` VARCHAR(250),`{col2}` VARCHAR(250),`{col3}` VARCHAR(250),`{col4}` VARCHAR(250)); """
    sql_command = q.format(col1=p[0], col2=p[1], col3=p[2], col4 = p[3])


>>> sql_command
' CREATE TABLE IF NOT EXISTS stud_data (`Last Name` VARCHAR(250),`First Name` VARCHAR(250),`Job` VARCHAR(250),`Country` VARCHAR(250)); '