Python连接数据库并插入数据

# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql

def dbHandle():
    conn = pymysql.connect(
        host='localhost',
        user='yourusername',
        passwd='yourpassword',
        charset='utf8',
        use_unicode=False
    )
    return conn
class CarPipeline(object):
    def process_item(self, item, spider):
        dbObject = dbHandle()
        cursor = dbObject.cursor()
        sql = 'insert into jobdata.qs_article(id,type_id,parentid,title,content,tit_color,tit_b,Small_img,author,source,focos,id_display,is_url,seo_keywords,seo_description,click,addtime,article_order,robot)' \
              'value' \
              '(%s,%s,%s,%s,%s,%s,0,%s,%s,%s,1,1,0%s,%s,1,%s,0,0)'
        try:
            cursor.execute(sql, (item['title'], item['content'],item['keywords']))
            dbObject.commit()
        except Exception, e:
            print e
            dbObject.rollback()
        return item

发表评论

电子邮件地址不会被公开。 必填项已用*标注