鍍金池/ 問答/Python  數(shù)據(jù)庫/ scrapy導(dǎo)入數(shù)據(jù)庫亂碼。

scrapy導(dǎo)入數(shù)據(jù)庫亂碼。

輸出打印沒有亂碼,插入到數(shù)據(jù)庫時亂碼。

數(shù)據(jù)庫的編碼:
圖片描述

piplines類的代碼如下:

class KGbookmysql(object):
    def process_item(self, item, spider):
        '''
        將爬取到的信息保存到mysql數(shù)據(jù)庫
        '''

        #將數(shù)據(jù)從item中提取出來
        title = item['title']
        author = item['author']
        score = item['score']
        peoples = item['peoples']
        #summary = item['summary']

        #和本地數(shù)據(jù)庫scrapydb建立連接
        db = pymysql.connect(
            host='localhost',
            #port=3306,
            user='root',
            password='******',
            db='scrapydb',
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )
        #獲取游標
        cursor = db.cursor()
        #有則刪除
        cursor.execute('drop table if exists kgbook')
        #創(chuàng)建表的sql語句
        sql1 = '''create table kgbook(
                id int primary key auto_increment,
                title varchar(60) not null,
                author varchar(60) not null,
                score varchar(30),
                peoples varchar(30)
                )ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
                AUTO_INCREMENT=1 ;
                '''
        cursor.execute(sql1)
        #db.close()
        sql_insert = '''insert into kgbook(title,author,score,peoples) values(%s,%s,%s,%s)'''

        try:
            with db.cursor() as cursor:
                cursor.execute(sql_insert, (title, author, score, peoples))
            db.commit()

        finally:
            db.close()

        return item

插入結(jié)果如下:
圖片描述

知道的前輩請指點錯誤在哪!感謝!

回答
編輯回答
傻叼

set names utf8;
select * from table;

還有問題再調(diào)整你客戶端工具的顯示字符集

2018年4月7日 05:32