【问题标题】:“Incorrect string value” when trying to insert String into MySQL via Python and Text file尝试通过 Python 和文本文件将字符串插入 MySQL 时出现“不正确的字符串值”
【发布时间】:2017-02-13 04:47:05
【问题描述】:

是什么导致了这个不正确的字符串?我已经阅读了很多问题和答案,这是我的结果。阅读答案后,我仍然遇到同样的错误。

我收到以下错误: ERROR 1366 (HY000) at line 34373: Incorrect string value: '\xEF\xBB\xBF<?x...' for column 'change' at row 1

当我尝试在 SQL 中输入以下内容时: 行号 34373:INSERT INTO gitlog_changes VALUES ('123456', 'NhincCommonEntity.xsd', '<?xml version=\"1.0\" encoding=\"UTF-8\"?>');

我的桌子是这样的:

DROP TABLE IF EXISTS `gitlog_changes`;
CREATE TABLE `gitlog_changes` (
  `hashID` varchar(40) NOT NULL,
  `filename` varchar(450) DEFAULT NULL,
  `change` mediumtext
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

我读了很多答案说将字符集更改为 UTF8 [1][2][3][4]。所以我执行这个: alter table yourTableName DEFAULT CHARACTER SET utf8;

我继续收到同样的错误。那我alter table yourTableName DEFAULT CHARACTER SET utf8mb4_general_ci;

仍然出现同样的错误。

我还尝试从 python 读取文件并直接提交到数据库。从这个答案[1]。我收到的是警告而不是错误。

我将以下代码插入到我的 python 脚本中:

    cursor.execute("SET NAMES 'utf8'")
    cursor.execute("SET CHARACTER SET utf8")

Python 脚本:

def insert_changes(modList):
    db = MySQLdb.connect("localhost", "user", "password", "table")
    cursor = db.cursor()

    cursor.execute("SET NAMES 'utf8'")
    cursor.execute("SET CHARACTER SET utf8")

    for mod in modList:
        hashID = mod["hashID"]
        fileName = mod["fileName"]
        change = mod["change"]

        cursor.execute("INSERT INTO gitlog_changes VALUES (%s, %s, %s" , (hashID, fileName, change))
    # # disconnect from server
    db.commit()
    db.close()

我在这里得到的警告是:Warning: Invalid utf8 character string: '\xEF\xBB\xBF<?x...' cursor.execute("INSERT INTO gitlog_changes VALUES (%s, %s, %s)" , (hashID, fileName, change))

【问题讨论】:

    标签: python mysql utf-8


    【解决方案1】:

    您尝试插入 db 的字符串在其开头有一个不寻常的字符。我刚刚复制了你的字符串:

    In [1]: a = '<'
    
    In [2]: a
    Out[2]: '\xef\xbb\xbf<'
    

    您需要摆脱这些字符。 This 是一篇很好的文章,解释了这些字符是什么。

    【讨论】:

      【解决方案2】:

      您尝试插入的文本在开头包含 UTF-8 BOM(即错误中的 \xEF\xBB\xBF)。

      check this answer 了解如何将带有 BOM 的 UTF-8 转换为 UTF-8。


      MySQL docs中所述

      MySQL 对 UTF-8 值不使用 BOM。

      所以唯一的解决方案是在你的 python 代码中解码这个字符串。

      【讨论】:

      • 我要在数据库中更改什么?
      • @Whitecat 正如我在编辑中提到的,唯一的方法是在你的 python 代码中解码字符串
      • 如果我错了,请纠正我。需要编辑所有字符串以将它们放入 SQL 中。如果我想使用文件,我什至必须从文件中编辑插入语句。
      • 我避免解码和编码的原因是这个答案:stackoverflow.com/questions/1168036/… 说这是个坏主意。
      • 精氨酸。我收到错误'utf8' codec can't decode byte 0xe9 in position 77: invalid continuation byte
      猜你喜欢
      • 2012-06-13
      • 2016-08-31
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      相关资源
      最近更新 更多