【问题标题】:Uploading Python Pandas dataframe to MySQL - InternalError: 1366, "Incorrect String Value"将 Python Pandas 数据帧上传到 MySQL - InternalError: 1366, "Incorrect String Value"
【发布时间】:2015-12-16 06:49:55
【问题描述】:

我正在尝试将 Pandas 数据框写入 MySQL 数据库,并使用了以下代码:

engine = sqlalchemy.create_engine("mysql+pymysql://root:password@localhost/skills?charset=utf8mb4")
connection = engine.connect
dataframe.head().to_sql('indeed_resumes', engine, flavor='mysql', if_exists='replace',index=True)

但是,我收到以下错误:

InternalError: (1366, "Incorrect string value: '\\xE1\\xBB\\x99i\\x0AO...' for column 'work' at row 5")

MySQL表的数据类型如下:

 mysql> desc indeed_resumes;
    +-----------+------------+------+-----+---------+-------+
    | Field     | Type       | Null | Key | Default | Extra |
    +-----------+------------+------+-----+---------+-------+
    | index     | bigint(20) | YES  | MUL | NULL    |       |
    | certs     | text       | YES  |     | NULL    |       |
    | contact   | text       | YES  |     | NULL    |       |
    | education | text       | YES  |     | NULL    |       |
    | headline  | text       | YES  |     | NULL    |       |
    | info      | text       | YES  |     | NULL    |       |
    | skills    | text       | YES  |     | NULL    |       |
    | summary   | text       | YES  |     | NULL    |       |
    | updated   | text       | YES  |     | NULL    |       |
    | work      | text       | YES  |     | NULL    |       |
    +-----------+------------+------+-----+---------+-------+
    10 rows in set (0.00 sec)

我的数据包含很长的字符串(有时大约 3000 个字符),因此这可能会导致错误。有什么建议吗?

【问题讨论】:

    标签: mysql pandas sqlalchemy


    【解决方案1】:

    我似乎已经解决了这个问题。看来我还需要使用以下命令更改数据库编码。

    ALTER DATABASE skills CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
    ALTER TABLE indeed_resumes CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    

    来自https://mathiasbynens.be/notes/mysql-utf8mb4

    “原来 MySQL 的 utf8 字符集仅部分实现了正确的 UTF-8 编码。它只能存储由 1 到 3 个字节组成的 UTF-8 编码符号;不支持占用 4 个字节的编码符号。

    幸运的是,MySQL 5.5.3(2010 年初发布)引入了一种名为 utf8mb4 的新编码,它映射到正确的 UTF-8,因此完全支持 Unicode,包括星体符号。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-18
      • 2019-02-27
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多