python爬取豆瓣兩千萬圖書簡介信息:(六)數(shù)據(jù)庫操作類

這是全部的調(diào)試過程,我已經(jīng)整理成為筆記,這里分享給大家:
python爬取豆瓣兩千萬圖書簡介信息:(一)目標API分析
python爬取豆瓣兩千萬圖書簡介信息:(二)簡單python請求urllib2
python爬取豆瓣兩千萬圖書簡介信息:(三)異常處理
python爬取豆瓣兩千萬圖書簡介信息:(四)多進程并發(fā)
python爬取豆瓣兩千萬圖書簡介信息:(五)數(shù)據(jù)庫設(shè)計
python爬取豆瓣兩千萬圖書簡介信息:(六)數(shù)據(jù)庫操作類
python爬取豆瓣兩千萬圖書簡介信息:(七)代理IP
python爬取豆瓣兩千萬圖書簡介信息:(八)總結(jié)

數(shù)據(jù)庫操作類

數(shù)據(jù)庫建好了,因為業(yè)務的單一性和頻發(fā)性,單獨做一個數(shù)據(jù)庫操作類在代碼管理上為好。

代碼如下:

# -*- coding:utf-8 -*-
import mysql.connector
import gc
import sys

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)

sys.setdefaultencoding(default_encoding)

def cb_conncet_sql(sql_query):
    # 創(chuàng)建數(shù)據(jù)庫連接方法
    config = {'host': 'localhost',
              'user': 'root',
              'password': 'root',
              'port': 3306,
              'database': 'doubanbook',
              'charset': 'utf8',
              'buffered': True
              }
    cnn = mysql.connector.connect(**config)
    try:
        cursor = cnn.cursor()
        cursor.execute(sql_query)
        cnn.commit()
        cds = cursor.fetchall()
        cb_print('查詢成功:'+ str(cds))
        return cds
    except mysql.connector.Error as e:
        if format(e) != 'No result set to fetch from.':
            cb_print('connect fails!{}'.format(e))
    finally:
        cursor.close()
        cnn.close()
        gc.collect()

def insert_book_info(par):
    # 解析bookinfo 并拼接SQL,插入數(shù)據(jù)庫
    if not par:
        cb_print('par 異常')
        return
    try:
        images = par['images']
        large_image = images['large']
        tags_dict = par['tags']
        tags = ''
        if tags_dict:
            for tag_item in tags_dict:
                tags = tags + tag_item['title'] + '&'
            tags = tags[:-1]
            tags = tags.replace('"', '')

        author_arr = par['author']
        author = ''
        if author_arr:
            for author_item in author_arr:
                author = author + author_item + '&'
            author = author[:-1]
            author = author.replace('"', '')

        rating = par['rating']
        average = rating['average']
        numraters = rating['numRaters']

        subtitle = par['subtitle']
        subtitle = subtitle.replace('"', '\'\'')
        if len(subtitle) > 250:
            subtitle = subtitle[0:250]

        title = par['title']
        title = title.replace('"', '\'\'')

        publisher = par['publisher']
        publisher = publisher.replace('"', '\'\'')

        binding = par['binding']
        binding = binding.replace('"', '\'\'')

        sql_query = ("INSERT INTO books (id, isbn13, publisher, pages,"
                     " title, image, alt, isbn10, "
                     "subtitle, "
                     "price, binding,"
                     "pubdate, large_image, "
                     "rating, numRaters,"
                     "tags, author) VALUES ("
                     + par['id'] + ','
                     + '"' + par['isbn13'] + '"' + ','
                     + '"' + publisher + '"' + ','
                     + '"' + par['pages'] + '"' + ','
                     + '"' + title + '"' + ','
                     + '"' + par['image'] + '"' + ','
                     + '"' + par['alt'] + '"' + ','
                     + '"' + par['isbn10'] + '"' + ','
                     + '"' + subtitle + '"' + ','
                     + '"' + par['price'] + '"' + ','
                     + '"' + binding + '"' + ','
                     + '"' + par['pubdate'] + '"' + ','
                     + '"' + large_image + '"' + ','
                     + '"' + str(average) + '"' + ','
                     + '"' + str(numraters) + '"' + ','
                     + '"' + tags + '"' + ','
                     + '"' + author + '"' + ');')
        cb_conncet_sql(sql_query)
    except Exception as e:
        if format(e) != 'No result set to fetch from.':
            cb_print('connect fails!{}'.format(e))
    finally:
        gc.collect()


def get_thread_index_id(index):
    # 獲取第index個進程的最大bookid
    try:
        sql = ('select max(id) from books WHERE id < '
               + str(1000000 + (index + 1) * 50000) + ';')
        cb_print(sql)
        result = cb_conncet_sql(sql)
        if not result:
            return 0
        else:
            re = result[0]
            if not re:
                return 0
            else:
                return re[0]
    except Exception as e:
        if format(e) != 'No result set to fetch from.':
            cb_print('connect fails!{}'.format(e))
    finally:
        gc.collect()


def insert_error_book_id(index):
    # 將異常bookid 插入 error_books表中
    try:
        sql = 'INSERT INTO error_books (bookid) VALUES (' + str(index) + ');'
        cb_conncet_sql(sql)
    except Exception as e:
        if format(e) != 'No result set to fetch from.':
            cb_print('connect fails!{}'.format(e))
    finally:
        gc.collect()


def insert_none_book_id(index):
    # 將不存在書目的bookid 插入 none_books表中
    try:
        sql = 'INSERT INTO none_books (bookid) VALUES (' + str(index) + ');'
        cb_conncet_sql(sql)
    except Exception as e:
        if format(e) != 'No result set to fetch from.':
            cb_print('connect fails!{}'.format(e))
    finally:
        gc.collect()


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,094評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,578評論 19 139
  • 需要原文的可以留下郵箱我給你發(fā),這里的文章少了很多圖,懶得網(wǎng)上粘啦 1數(shù)據(jù)庫基礎(chǔ) 1.1數(shù)據(jù)庫定義 1)數(shù)據(jù)庫(D...
    極簡純粹_閱讀 7,911評論 0 46
  • zhangcarming閱讀 192評論 0 0
  • 一棵樹喝多了陽光 長上山頂 搖晃 快樂 風是知道的 根往山腳下走 蔓延 痛苦 溪流知道 湖清楚知道 路過的...
    李唐的小詩閱讀 371評論 0 12

友情鏈接更多精彩內(nèi)容