Python 3+;Mysql:不正确的字符串值'\xF0\x9F\x85\x97\xF0\x9F…&x27;

Python 3+;Mysql:不正确的字符串值'\xF0\x9F\x85\x97\xF0\x9F…&x27;,python,mysql,python-3.x,character-encoding,Python,Mysql,Python 3.x,Character Encoding,我在堆栈中找到了关于“字符串值不正确”的其他问题/答案,但没有一个答案有效,因此我的案例可能有所不同 try: self.cnx = mysql.connector.connect(host='localhost', user='emails', password='***', database='extractor', raise_on_warnings=True) except mysql.

我在堆栈中找到了关于“字符串值不正确”的其他问题/答案,但没有一个答案有效,因此我的案例可能有所不同

try:
    self.cnx = mysql.connector.connect(host='localhost', user='emails', password='***',
                                               database='extractor', raise_on_warnings=True)
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)
self.sql = self.cnx.cursor()

biography = str(row[8])
self.sql.execute("""insert into emails (biography)
                            values(%s)""",
                                         (biography,))
其中,
传记
是以下内容的
utf8mb4_general_ci
文本列:


emails.biography
VARCHAR
类型,并且
emails
字符集是
utf8mb4
。如果不是,则您希望执行:

 ALTER TABLE `emails` CONVERT TO CHARACTER SET utf8mb4;
然后,如果这不能解决问题,请在Python中创建MySQL游标后直接尝试执行以下操作(假设
self.sql
是游标):

如果这不起作用,请在Python中创建MySQL连接后立即尝试设置字符集,例如:

 self.connection.set_character_set('utf8mb4')
如果此时您仍然运气不佳,我们可以进一步调试:)

更新:

尝试:


请注意,
utf8mb4\u general\u ci
是表的排序规则,而不是编码。理想情况下,您应该使用
COLLATE utf8\u unicode\u ci

'<让我们看看python中的连接参数。问题已更新。它是一个已经是文本类型的uft8bm4字段。问题已更新。
self.cnx.set\u character\u set('utf8mb4')
产生:
AttributeError:'MySQLConnection'对象没有属性'set\u character\u set'
所以我不得不做:
self.cnx.set\u排序规则('utf8bm4')
产生:
不支持字符集'utf8bm4'。
。我还尝试了
utf8bm4\u general\u ci
,结果相同。尝试将所有
utf8mb4
更改为
utf8
<代码>utf8mb4
是在MySQL版本5.5中引入的,所以您可能正在使用一个相当旧的MySQL安装。另外,我已经更新了我的答案。你能粘贴你的
my.cnf
?如果尚未更新,则可能应该更新它。请参见此处:。如果你把你现在有的东西寄给我,我可以帮你。太好了!这救了我一天。我一直在尝试使用Python将Emojis放入MySQL,但没有成功。第二个解决方案(执行
设置名称utf8mb4
和其他查询)对我来说效果不错。顺便说一下,这应该是可以接受的答案。我不知道为什么不是。
 self.connection.set_character_set('utf8mb4')
ALTER TABLE `emails` CONVERT TO CHARACTER SET utf8;
ALTER TABLE `emails` CHANGE COLUMN `biography` TEXT CHARACTER SET 'utf8';