Python爬虫之Emoj表情无法插入数据库Mysql



#1.修改配置文件my.ini

[client]

port=3306

default-character-set=utf8mb4

[mysql]

port=3306

default-character-set=utf8mb4

[mysqld]

port=3306

character-set-client-handshake= FALSE

character-set-server= utf8mb4

collation-server= utf8mb4_unicode_ci

init_connect='SET NAMES utf8mb4'

重启mysql服务,可用以下代码检验是否修改成功:

SHOWVARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE'collation%';

#2.代码优化



在创建连接后,对游标执行‘SET NAMES utf8mb4;’:

SET NAMES utf8mb4;

Python代码如下:

def data_import(sql):
    flag=False
    db = MySQLdb.connect(host='localhost',port=3307,user='root',passwd='',db='py_comment',charset='utf8')
    cursor = db.cursor()
    cursor.execute("SET NAMES utf8mb4;")
    try:
        cursor.execute(sql)
        db.commit()
        flag=True
    except:
        db.rollback()
        db.close()
        flag=False
    db.close()
    return flag

你可能感兴趣的:(服务器,python,mysql)