scrapy 使用pymysql操作数据库的两个问题。

已解决:
1.乱码问题:Windows下向mysql写入数据前set names gbk;,关闭mysql后失效。
2.只能写入最后一个item:去除删除表的代码。创建表的sql语句改为
create table IF NOT EXISTS ysw()

———————————————————————————————————————
1. 将item写入数据库只能写进去最后一个item
2. 写进去的汉字乱码

pipeline类如下:

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

        #创建数据库连接,格式为utf8
        conn = pymysql.connect(
            host='localhost',
            user="root",
            passwd="******",
            db='pymysql_db',
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor
        )

        cursor = conn.cursor()
        #使用execute方法执行这条sql语句: 如果ysw表已经存在,则删除
        cursor.execute("drop table if exists ysw")
        #创建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;'''
                #执行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

结果:

黑色框是mysql客户端命令行查看结果,显示汉字是乱码。
白色框里是mysql的图形管理工具查看结果,汉字没有乱码。

图片描述

为什么mysql里面显示会是乱码呢?
为什么只写进去了获得的最后一个item呢?

请知道怎么处理的前辈教我,感谢!感谢!

阅读 5.8k
2 个回答

1、建表语句,每次都删除再创建,所以只有最后一条记录,建议提前把表建好,不要放在这里建表,或者做一下是否存在该表就不创建,不要删除表。
2、命令行,需要设置字符集

set names utf8;

居然把drop/create table放代码里,难不成每次运行都执行一遍?
乱码问题是命令行读取数据是不是没有设置字符集,使用set names utf8之后再读一次看下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题