我的测试代码如下
import pymysql
db = pymysql.connect('localhost', 'root', '000aaa', 'test')
cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS ddbooks')
sql1 = 'CREATE TABLE IF NOT EXISTS ddbooks(\
id INT PRIMARY KEY AUTO_INCREMENT,\
main_classify VARCHAR(10) NOT NULL,\
secondary_classify VARCHAR(10) NOT NULL,\
classify VARCHAR(10) NOT NULL,\
book_title VARCHAR(160),\
author VARCHAR(20),\
now_price VARCHAR(7),\
pre_price VARCHAR(7),\
discount VARCHAR(6),\
publisher VARCHAR(20),\
intro TEXT);'
item = {'教育': \
{'外语':\
{'英语综合教程':\
{'现价': '15.10', \
'书名': '剑桥初级英语语法练习(第三版中文版)(剑桥英语在用丛书) [Essential Grammar in Use]英语学习者的圣经,全球销量逾千万,源自剑桥,口碑佳作。左手页讲解,右手页练习,学练结合,培训自学均适用.在语境中学习语言,在体验中学以致用', \
'作者': '(英)海伦.内勒(Helen Naylor),雷蒙德?墨菲(Ra', \
'简介': '《剑桥初级英语语法练习(第三版中文版)》编辑推荐: 来自全球*畅销的英语学习参考书 剑桥 英语在用 (English in Use)系列 习题生动有趣,内容涉及日常生活、娱乐、文化、侦查破案、采访等,做习题也快乐 习题语言口语和书面语兼顾,做习题的同时可提高口语和写作水平 答案详尽,随时自测学习效果 集权威和趣味于一体的语法练习册!', \
'折扣率': '8.89', \
'出版社': '外语教学与研究出版社', \
'原价': '17.00'}}}}
sql2 = 'INSERT INTO ddbooks VALUES(NULL, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);'
gftype = list(item.keys())[0]
ftype = list(item[gftype].keys())[0]
kind = list(item[gftype][ftype].keys())[0]
info = item[gftype][ftype][kind]
cursor.execute(sql1)
cursor.execute(sql2 % (gftype, ftype, kind, info['书名'], info['作者'], info['现价'],info['原价'], info['折扣率'], info['出版社'], info['简介']))
db.close()
报错如下:
Traceback (most recent call last):
File "test.py", line 25, in <module>
cursor.execute(sql2 % (gftype, ftype, kind, info['书名'], info['作者'], info['现价'],info['原价'], info['折扣率'], info['出版社'], info['简介']))
File "/home/thepoy/.local/lib/python3.5/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/home/thepoy/.local/lib/python3.5/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/home/thepoy/.local/lib/python3.5/site-packages/pymysql/connections.py", line 517, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/home/thepoy/.local/lib/python3.5/site-packages/pymysql/connections.py", line 732, in _read_query_result
result.read()
File "/home/thepoy/.local/lib/python3.5/site-packages/pymysql/connections.py", line 1075, in read
first_packet = self.connection._read_packet()
File "/home/thepoy/.local/lib/python3.5/site-packages/pymysql/connections.py", line 684, in _read_packet
packet.check_error()
File "/home/thepoy/.local/lib/python3.5/site-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/home/thepoy/.local/lib/python3.5/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(剑桥英语在用丛书) [Essential Grammar in Use]英语学习者的圣经,' at line 1")