MySQL Error:Warning: (1366, "Incorrect string value: '\\xF0\\x9F\\x98\\x82\\xF0\\x9F...' for column 'xxx' at row 2")


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;")

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM