python,mysql和utf8mb4编码麻烦

时间:2018-08-14 15:10:40

标签: mysql python-3.x character-encoding sqlalchemy pymysql

当尝试将简单数据框保存到mysql时,出现以下警告:

  

C:... \ anaconda3 \ lib \ site-packages \ pymysql \ cursors.py:170:警告:(1366,“不正确的字符串值:'\ x92 \ xE9t \ xE9)'位于'VARIABLE_VALUE'列518“)     结果= self._query(查询)

  

C:... anaconda3 \ lib \ site-packages \ pymysql \ cursors.py:170:警告:   (3719,“'utf8'当前是字符集UTF8MB3的别名,   但它将在将来的版本中成为UTF8MB4的别名。请考虑   使用UTF8MB4以便明确。“)result =   self._query(query)

环境信息:我使用Mysql8,python3.6(pymysql 0.9.2,sqlalchemy 1.2.1)

我访问了一个类似波纹管的帖子,似乎都没有提供有关如何避免此警告的解决方案。

N.B:mysql表中的归类似乎未设置为我在create_db类的Connection函数中指定的归类。

可执行代码:

import DataEngine.db.Connection as connection
import random
import pandas as pd

if __name__ == "__main__":
    conn = connection.Connection(host="host_name", port="3306", user="username", password="password")
    conn.create_db("raw_data")
    conn.establish("raw_data")
    l1 = []
    for i in range(10):
        l_nested = []
        for j in range(10):
            l_nested.append(random.randint(0, 100))
        l1.append(l_nested)
    df = pd.DataFrame(l1)

    conn.save(df, "random_df")
    df2 = conn.retrieve("random_df")
    print(df2)

因此数据库中保留的数据框为:

   index   0   1   2   3   4   5   6   7   8   9
0      0  11  57  75  45  81  70  91  66  93  96
1      1  51  43   3  64   2   6  93   5  49  40
2      2  35  80  76  11  23  87  19  32  13  98
3      3  82  10  69  40  34  66  42  24  82  59
4      4  49  74  39  61  14  63  94  92  82  85
5      5  50  47  90  75  48  77  17  43   5  29
6      6  70  40  78  60  29  48  52  48  39  36
7      7  21  87  41  53  95   3  31  67  50  30
8      8  72  79  73  82  20  15  51  14  38  42
9      9  68  71  11  17  48  68  17  42  83  95

我的Connection class

import sqlalchemy
import pymysql
import pandas as pd


class Connection:
    def __init__(self: object, host: str, port: str, user: str, password: str):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.conn = None

    def create_db(self: object, db_name: str, charset: str = "utf8mb4", collate:str ="utf8mb4_unicode_ci",drop_if_exists: bool = True):
        c = pymysql.connect(host=self.host, user=self.user, password=self.password)
        if drop_if_exists:
            c.cursor().execute("DROP DATABASE IF EXISTS " + db_name)
        c.cursor().execute("CREATE DATABASE " + db_name + " CHARACTER SET=" + charset + " COLLATE=" + collate)
        c.close()
        print("Database %s created with a %s charset" % (db_name, charset))

    def establish(self: object, db_name: str, charset: str = "utf8mb4"):
        self.conn = sqlalchemy.create_engine(
            "mysql+pymysql://" + self.user + ":" + self.password + "@" + self.host + ":" + self.port + "/" + db_name +
            "?charset=" + charset)
        print("Connection with database : %s has been established as %s at %s." % (db_name, self.user, self.host))
        print("Charset : %s" % charset)

    def retrieve(self, table):
        df = pd.read_sql_table(table, self.conn)
        return df

    def save(self: object, df: "Pandas.DataFrame", table: str, if_exists: str = "replace", chunksize: int = 10000):
        df.to_sql(name=table, con=self.conn, if_exists=if_exists, chunksize=chunksize)

一些可能有用的元素: Database is of charset utf8mb4 Table columns don't seem to have the correct collation even though I specified it when creating the db

1 个答案:

答案 0 :(得分:1)

嗯,十六进制92和e9无效utf8mb4(UTF-8)。假设您是’été,假设使用CHARACTER SETs cp1250,cp1256,cp1257或latin1。

找出该文本来自何处,然后决定它是否有效latin1然后我们可以修复代码以声明客户端确实在使用latin1,而不是utf8mb4?或者,我们可以修复客户端以使用UTF-8,从长远来看,这可能会更好。