import pymysql as pq
class Pipeline(object): def init(self): self.conn = pq.connect(host='127.0.0.1', user='root',port='3306', passwd='123456', db='root', charset='utf8') self.cur = self.conn.cursor() # def init(self): # host = '127.0.0.1' # port = 27017 # client = pymongo.MongoClient(host=host,port=port) # collection = client.local.letsgojpt # self.post = collection
def process_item(self, item, spider):
    for i in range(0,len(item["title_all"])):
        # sql = "insert into letsgojp(title_all, center_all) VALUES (%s, %s)"
        self.cur.execute("insert into letsgojp(title_all,center_all) values(%s,%s)",(item['title_all'][i],item['center_all'][i]))
        self.conn.commit()
        # self.post.insert(data)
    return item
def close_spider(self, spider):
    self.cur.close()
    self.conn.close()
主要是这行报错
self.cur.execute("insert into letsgojp(title_all,center_all) values(%s,%s)",(item['title_all'][i],item['center_all'][i]))
用 mongo 的时候是正常存数据的,但是用 mysql 就报错,网上找一些,不太会用,请教各位大神了
|  |      1ClericPy      2020-05-07 21:56:44 +08:00 1. 找个贴代码的地方把缩进留下... 2. 报错信息解释 90% 问题, 大部分时间报错信息最后一行一搜 stackoverflow 上都有同行遇到过 3. 纯看的话, 实在猜不到啊... 就语法来说, pymysql 会自动转义, 问题不大, 看你的列名也没有敏感关键字所以不加反引号也没事 | 
|  |      2jugelizi      2020-05-07 22:00:52 +08:00 [item['title_all'][i],item['center_all'][i]]  是不是? 也有可能没处理好特殊字符 错误提示贴下啊 | 
|  |      4chaneyccy      2020-05-07 22:55:09 +08:00 不贴报错信息,这也看不出来哪里有问题吧 没用过 SQL 好奇搜了一圈,没有发现模块导入是 import pymysql as pq,问题在这? | 
|      5Colorful OP @chaneyccy 不是那里,能爬到一条数据  self.cur.execute("insert into letsgojp(title_all,center_all) values(%s,%s)",(item['title_all'][i],item['center_all'][i])) 主要就是这行 | 
|  |      6aydd2004      2020-05-07 23:17:58 +08:00 execute 的内容 print 出来看一下  实在不行粘到 mysql 里面执行一下 | 
|      7dorothyREN      2020-05-08 00:01:50 +08:00 占位符那里的问题,插入字符串 需要 加上 \'%s\' | 
|      8dorothyREN      2020-05-08 00:06:12 +08:00 @dorothyREN #7 ```    def save_data(self, title, content): sql = "INSERT INTO test(title,content) VALUES (\'%s\',\'%s\')" % (title, content) # print(sql) self.cur.execute(sql) self.conn.commit() ``` | 
|  |      9crella      2020-05-08 07:24:08 +08:00 via Android mysql 新版的 mb-utf8 编码设置有点麻烦。 建议直接 postgresql | 
|  |      10triangle111      2020-05-08 08:51:33 +08:00 print 一下 sql 语句到 mysql 执行就知道错哪了, 应该是字符串没有引号导致的吧 | 
|      11annielong      2020-05-08 09:20:56 +08:00 一般都是编码和非法字符的问题,打印 sql 语句就可以看出来 | 
|      12zhangysh1995      2020-05-08 13:58:46 +08:00 添加 try except,抓 mysql.connector.errors.DatabaseError 错误 | 
|      13leapV3      2020-05-08 15:04:30 +08:00 你试试将表名与列名加上反引号 | 
|  |      14AmberJiang      2020-05-08 16:19:26 +08:00 感觉像是 insert 语句那里存在语法错误。。。贴报错图出来看看吧 |