2014-01-08 56 views
0

SO是新手,對編碼來說相當新穎,所以盡我所能去遵循適當的協議。使用列表創建一個MySQL表的列

在我的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") 
+2

列規範需要數據類型。 – eggyal

+0

謝謝eggyal!這解決了它! –

回答

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)