鍍金池/ 問答/人工智能  Python  數(shù)據(jù)庫/ scrapy 使用pymysql操作數(shù)據(jù)庫的兩個問題。

scrapy 使用pymysql操作數(shù)據(jù)庫的兩個問題。

已解決:
1.亂碼問題:Windows下向mysql寫入數(shù)據(jù)前set names gbk;,關(guān)閉mysql后失效。
2.只能寫入最后一個item:去除刪除表的代碼。創(chuàng)建表的sql語句改為
create table IF NOT EXISTS ysw()

———————————————————————————————————————
1. 將item寫入數(shù)據(jù)庫只能寫進去最后一個item
2. 寫進去的漢字亂碼

pipeline類如下:

class Pymsql_Pipelnie(object):
    def process_item(self, item, spider):

        #創(chuàng)建數(shù)據(jù)庫連接,格式為utf8
        conn = pymysql.connect(
            host='localhost',
            user="root",
            passwd="******",
            db='pymysql_db',
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor
        )

        cursor = conn.cursor()
        #使用execute方法執(zhí)行這條sql語句: 如果ysw表已經(jīng)存在,則刪除
        cursor.execute("drop table if exists ysw")
        #創(chuàng)建ysw表,格式為utf8
        create_ysw = '''
                create table ysw(
                    id int not null primary key auto_increment,
                    time varchar(20),
                    author varchar(30),
                    agree varchar(20),
                    sec_num varchar(20)  
                )ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
                AUTO_INCREMENT=1;'''
                #執(zhí)行create_ysw語句
        cursor.execute(create_ysw)

        with conn.cursor() as cursor:
            time = item['time']
            author = item['author']
            agree = item['agree']
            sec_num = item['sec_num']

            sql_2 = "insert into ysw(time, author, agree, sec_num) values(%s, %s, %s, %s);"
            try:
                cursor.execute(sql_2, (time, author, agree, sec_num))
                conn.commit()
            except Exception as e:
                print(e)

        return item

結(jié)果:

黑色框是mysql客戶端命令行查看結(jié)果,顯示漢字是亂碼。
白色框里是mysql的圖形管理工具查看結(jié)果,漢字沒有亂碼。

圖片描述

為什么mysql里面顯示會是亂碼呢?
為什么只寫進去了獲得的最后一個item呢?

請知道怎么處理的前輩教我,感謝!感謝!

回答
編輯回答
瞄小懶

1、建表語句,每次都刪除再創(chuàng)建,所以只有最后一條記錄,建議提前把表建好,不要放在這里建表,或者做一下是否存在該表就不創(chuàng)建,不要刪除表。
2、命令行,需要設(shè)置字符集

set names utf8;
2018年8月13日 11:31
編輯回答
默念

居然把drop/create table放代碼里,難不成每次運行都執(zhí)行一遍?
亂碼問題是命令行讀取數(shù)據(jù)是不是沒有設(shè)置字符集,使用set names utf8之后再讀一次看下

2017年4月15日 00:57