所以我有一堆Python中的數組數據。那麼,我有一個列表清單。我試圖將這個數組存儲到MySQL數據庫中的一個單元中。我試圖使用JSON來序列化我的數據,但也許我不明白JSON是如何工作的。插入Python列表(JSON或其他)到MySQL數據庫
所以連接到我的數據庫後:(我試過LONGTEXT LONGBLOB和數據類型上下游
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS 963168MBV17A(Id INT AUTO_INCREMENT PRIMARY KEY, Rev INT, Part VARCHAR(15), SN INT(7), Date DATE, Time TIME, Iterations INT(3), Upstream LONGBLOB, Downstream LONGBLOB, ResultList LONGTEXT, Result CHAR(1), Report LONGBLOB)")
我把我的表稱爲upstream_data和downstream_data的列表,並做到:
export_upstream = json.dumps(upstream_data)
export_downstream = json.dumps(downstream_data)
然後我執行SQL命令:
cur = con.cursor()
sql_input = "INSERT INTO 963168MBV17A(Rev, Part, SN, Iterations, Date, Time, Upstream, Downstream, ResultList, Result, Report) VALUES('503', '100-120970-0031', '1594539', '%s', '%s', '%s', '%s', '%s', 0, P, 0" %(export_date, export_time, export_numtests, export_upstream, export_downstream)
cur.execute(sql_input)
引用一個回答[R由Mordi(http://stackoverflow.com/questions/4251124/inserting-json-into-mysql-using-python),我甚至試過:
export_upstream = json.dumps(json.dumps(upstream_data))
export_downstream = json.dumps(json.dumps(downstream_data))
但不管我最終錯誤:
Traceback (most recent call last):
File "P:\Projects\testing database\scrap\test.py", line 83, in <module>
cur.execute(sql_input)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
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")
而且,當我做了
print "about to execute(%s)" % sql_input
我看到JSON對象表現爲一個長字符串,有很多單引號的所有的地方(的名單,並在外面代表一個字符串)。當我做了json.dumps(json.dumps(upstream_data))時,內部引號變成了雙引號「」,前面加了\字符。儘管如此,我也遇到了同樣的錯誤。
任何想法?如果沒有,更好的方法來將Python數組/列表數據存儲到單個MySQL單元中?
輸出here
工作就像一個魅力,謝謝 – sirgogo