0
這讓我瘋狂了兩天。我想添加一個2D列表到MySQL數據庫。我的代碼如下:將列表添加到mysql數據庫
import MySQLdb as mdb
i = 0
ins = open("test.txt", "r")
skeds = []
for line in ins:
i = i + 1
line = line.replace(",", "")
#line = line.replace('""', "")
line = line.replace("\xc2\xa0", "EMPTY")
line = line.replace("\xef\xbb\xbf", "")
line = line.strip()
line = line.strip().upper()
line = line.split('""')
line = filter(None, line)
skeds.append(line)
del skeds[i-1]
print(skeds[277])
con = mdb.connect('localhost', 'testuser', 'test123', 'sked')
with con:
#AT this point sked = ['WATCH', 'VT-X', 'EMPTY', '10:30', '15:00', 'EMPTY', 'DOE JON [1XX]', 'PM SDO', '4.5', 'EMPTY', 'EMPTY']
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS test3")
cur.execute("CREATE TABLE test3(Type VARCHAR(50), VT VARCHAR(50), Brief VARCHAR(50), EDT VARCHAR(50), RTB VARCHAR(50), Instructor VARCHAR(50), Student VARCHAR(50), Event VARCHAR(50), Hrs VARCHAR(50), Remarks VARCHAR(75), Location VARCHAR(50))")
params = "INSERT INTO test3(Type, VT, Brief, EDT, RTB, Instructor, Student, Event, Hrs, Remarks, Location) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
dats = skeds[36]
cur.executemany(params, dats)
下面是我得到一個錯誤:
smartsked Main$ python sked1.py
['WATCH', 'VT-9', 'EMPTY', '10:30', '15:00', 'EMPTY', 'SENG PATRICK [1STLT]', 'PM SDO', '4.5', 'EMPTY', 'EMPTY']
Traceback (most recent call last):
File "sked1.py", line 36, in <module>
cur.executemany(params, dats)
File "/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.11-x86_64.egg/MySQLdb/cursors.py", line 244, in executemany
self.errorhandler(self, ProgrammingError, msg.args[0])
File "/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.11-x86_64.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: not enough arguments for format string
有什麼建議?我還想在我的skeds列表中迭代executemany函數,以便將完整的2d列表放入數據庫中。
你已經打印skeds [277],但你試圖插入skeds [36]。這包含什麼? –
你確定你粘貼了正確的縮進嗎?原因'skeds.append(line)'只會追加一行,您立即刪除,下一行會出錯。所以我猜不是? –
@DanielRoseman - 無論是skins [277]還是skeds [36]都包含相同數量的信息,只是不同的字符串。您可以在錯誤打印輸出中看到skeds [277]的打印輸出。 [36]與不同的字符串是一樣的。 – exos