使用List创建MySQL表的列

时间:2014-01-08 23:28:17

标签: 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")
    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")

1 个答案:

答案 0 :(得分:1)

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

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)