bug现象

使用连接数据库的可视化软件插入 emoj 表情数据、生僻字,可以正常插入。(导致我一直以为跟表情没有任何关系,谷歌出来一堆跟修改数据库、表、字段 的编码的结果....)但是一启动程序插入新数据就会报这个错误,一一检查过数据库、表、字段的编码都是正确的,后面只能把插入数据的代码撸下来单独跑,在代码里面尝试插入 生僻字、emoj 表情,终于重现了bug。。。 然后谷歌的关键词转向了 python。

 

peewee 解决方法

  

# 1、创建连接
cache_database = PooledMySQLDatabase(
    "database",
    **{
        "host": "xxx",
        "port": 3306,
        "user": "xxx",
        "password": "xxx"
    }
)


# 2、获取游标
cursor = cache_database.cursor()
# 3、划重点:修改数据库连接是以utf8mb4编码格式进行的连接
cursor.execute('SET NAMES utf8mb4;')


# 4、定义模型类
class BaseModel(Model):
    class Meta:
        database = cache_database


class TestModel(BaseModel):
    id = BigIntegerField(primary_key=True, sequence=True)
    code = FixedCharField(max_length=32, default='')
    。。。

    class Meta:
        db_table = 'test_table'


# 5、插入数据
def retry_store_cache(db, table, cache_info_list):
    n = 1
    while True:
        try:
            if db.is_closed():
                db.connect()
            if not table.table_exists():
                table.create_table()
            with db.atomic():
                table.insert_many(cache_info_list).execute()
        except Exception as e:
            print("<error>: {}".format(e.with_traceback(sys.exc_info()[2])))
            print("retry store data {}s later".format(n))
            time.sleep(n)
            n *= 2
            if n > 8:
                raise Exception(e)
        else:
            break


data_info = [    
    {
        'ratio': 1.0,
        'city': 340,
        'poi': 4075062903,
        'code': '5193fb98f2307202858f8ec6644f58e5',
        'create_time': 1574714741,
        'data': '😂😂😂😂😂😂'
    }
]
retry_store_cache(cache_database, TestModel, cache_info)

 

  

以下转自:https://www.2cto.com/database/201405/303550.html

MySQLdb 解决方法

# 1、创建连接
conn = MySQLdb.connect(host=host, user=username, passwd=passwd, db=dbname, charset='utf8')

# 2、获取游标
cursor = conn.cursor()

# 3、执行连接对象的编码修改语句
cursor.execute("SET NAMES utf8mb4;")

 

 

SQLalchemy 解决方法

conn = "mysql+mysqldb://%s?use_unicode=0&charset=utf8" % server
engine = create_engine(conn, encoding='utf-8', echo=False)
engine.execute("SET NAMES utf8mb4;")

 

  

 

 posted on 2019-12-06 16:10  lin-gooo  阅读(2915)  评论(0编辑  收藏  举报