Python 创建MySQL表';用列表替换列

Python 创建MySQL表';用列表替换列,python,mysql,sql,Python,Mysql,Sql,不熟悉SO,也不太熟悉编码,所以我会尽我所能遵循适当的协议 在我的python脚本中,我创建了一个新表,并从名为“dups”的列表中填充列名 dups = ['Id', 'Name', 'Price', 'Rating'] 我通过for循环输入这个列表作为新表的列,称为“SuperTable”。见下面的代码: with new_db: cur = new_db.cursor() cur.execute("DROP TABLE IF EXISTS SuperTable")

不熟悉SO,也不太熟悉编码,所以我会尽我所能遵循适当的协议

在我的python脚本中,我创建了一个新表,并从名为“dups”的列表中填充列名

dups = ['Id', 'Name', 'Price', 'Rating']
我通过for循环输入这个列表作为新表的列,称为“SuperTable”。见下面的代码:

with new_db:

    cur = new_db.cursor()
    cur.execute("DROP TABLE IF EXISTS SuperTable")
    for i in dups:
        if i == dups[0]:
            new_col = i.replace("'","")
            cur.execute("CREATE TABLE SuperTable(%s)" % (new_col))
    else:
        cur.execute("ALTER TABLE SuperTable ADD COLUMN %s" % i)
我环顾了很多地方,似乎无法确定我做错了什么。这种方法适用于Sqlite,但我一直在MySQLdb中遇到同样的错误:

Traceback (most recent call last):
  File "MySQL_SuperTable.py", line 125, in <module>
  cur.execute("CREATE TABLE Super(%s)" % (new_col))
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/cursors.py", line 174, in execute
  self.errorhandler(self, exc, value)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
  raise errorclass, errorvalue
  _mysql_exceptions.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 ')' at line 1")
回溯(最近一次呼叫最后一次):
文件“MySQL_SuperTable.py”,第125行,在
当前执行(“创建超级表(%s)”%(新列))
文件“/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site packages/MySQLdb/cursors.py”,执行中的第174行
errorhandler(self、exc、value)
defaulterrorhandler中的文件“/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site packages/MySQLdb/connections.py”,第36行
提高errorclass,errorvalue
_mysql_exceptions.ProgrammingError:(1064,“您的SQL语法有错误;请查看与您的mysql服务器版本对应的手册,以了解可在第1行“near”)中使用的正确语法)

多亏了eggyal!他指出MySQL列需要数据类型。这就是代码现在的样子(我创建了一个元组列表,通过for循环输入数据类型+列名):

带有新的\u db:
cur=new_db.cursor()
当前执行(“如果存在超级表,则删除表”)
对于col_名称类型中的i:
如果i==col_namestypes[0]:
当前执行(“创建表超级表(%s%s)”%(i))
其他:
当前执行(“ALTER TABLE SuperTable ADD列%s%s”%i)
对于新表中的i:
计数=len(i)
问号=[]
而a<计数:
问号。追加(“%s”)
a+=1
任务=','。加入(问号)
当前ExecuteMy(“插入到超级表值(%s)”%quests,新表)

列规格要求数据类型。谢谢eggyal!这就解决了!
with new_db:

cur = new_db.cursor()
cur.execute("DROP TABLE IF EXISTS SuperTable")
for i in col_namestypes:
    if i == col_namestypes[0]:
        cur.execute("CREATE TABLE SuperTable(%s %s)" % (i))
    else:
        cur.execute("ALTER TABLE SuperTable ADD COLUMN %s %s" % i)
for i in new_table:
    count = len(i)
question_marks = []
while a < count:
    question_marks.append('%s')
    a += 1
quests = ','.join(question_marks)
cur.executemany("INSERT INTO SuperTable VALUES(%s)" % quests, new_table)