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")
列規範需要數據類型。 – eggyal
謝謝eggyal!這解決了它! –