【问题标题】:Wrong letters after adding strings into database Python将字符串添加到数据库Python后出现错误的字母
【发布时间】:2012-06-02 06:36:03
【问题描述】:

通过 Python 将大约 6k 行添加到我的 mySQL 数据库后,一些字母是错误的(波兰字母),例如 Å‚ 代表 ł 和 ż 代表 ż 等。我该如何修复它?我的python代码是:

 # -*- coding: utf-8 -*-
import MySQLdb
import string
import codecs
file = codecs.open("----", 'r', 'utf-8')
db = MySQLdb.connect(host="-----", port=3306, user="-----", passwd="------", db="----")
cursor = db.cursor()
for line in file:
        lines = string.replace(line, "'", '"')
        cursor.execute("INSERT INTO Logs (Text) VALUE ('%s')"% lines.encode("utf-8"))
db.close()
print("done")

运行这段代码后,运行正常,但是在 PhpMyAdmin 中,出现了错误的字母。 数据库中的编码是 UTF-8,文件是 ANSI 为 UTF-8(来自记事本++)。 有什么帮助吗?

【问题讨论】:

  • 你确定 PHPMyAdmin 不只是显示错误吗?您可能想查看stackoverflow.com/questions/4777900/…
  • 它显示正确,下面的答案是让它工作。
  • 使用参数化 sql 代替 Python 字符串插值
  • 而不是cursor.execute("INSERT INTO Logs (Text) VALUE ('%s')"% lines.encode("utf-8")),最好是cursor.execute("INSERT INTO Logs (Text) VALUE (%s)", lines.encode("utf-8"))

标签: python mysql text


【解决方案1】:

MySQLdb.connect()中指定字符集:

db = MySQLdb.connect(host="-----", port=3306, user="-----",
    passwd="------", db="----", charset='utf8')

【讨论】:

  • 小改动,没有“-”的 utf8 并且有效,谢谢,我会在几分钟后将此添加为已接受的答案
猜你喜欢
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
  • 2020-10-05
相关资源
最近更新 更多