【问题标题】:Getting error when INSERT into MySQL插入 MySQL 时出错
【发布时间】:2010-12-20 23:25:28
【问题描述】:
_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1


def getSource(theurl, moved = 0):
    if moved == 1:
        theurl = urllib2.urlopen(theurl).geturl()
    urlReq = urllib2.Request(theurl)
    urlReq.add_header('User-Agent',random.choice(agents))
    urlResponse = urllib2.urlopen(urlReq)
    htmlSource = urlResponse.read()
    return htmlSource

new_u = Url(source_url = source_url, source_url_short = source_url_short, source_url_hash = source_url_hash, html = htmlSource)
new_u.save()

为什么会这样? 我基本上是在下载页面的 URL...然后使用 Django 将其保存到数据库中。

它只是有时会发生......有时它工作正常。

编辑:好像我必须将数据库设置为 UTF-8?执行此操作的命令是什么?

【问题讨论】:

  • 执行查询的代码请...
  • 鲍比,查询是 new_u, new_u.save() 。这是 Django 查询
  • @alex:哦……从来没有使用过那个系统。最好的猜测是,您没有转义 html-String,而他正试图插入“错误”值。对于 PHP,该功能称为 mysql_real_escape_string。

标签: python mysql html database django


【解决方案1】:

如果您想更改 MySQL 中的字符集,有两种方法。 首先是数据库的默认值,见MySQL Alter database, 第二个是每个表:MySQL Alter Table

我相信,数据库为新表提供了默认字符集。这 可以在每个表的基础上覆盖,你需要这样做,因为你 已经有桌子了。 “utf8”是受支持的字符集。

也可以看看Blog about UTF8 with django and MySQL

【讨论】:

    【解决方案2】:

    您基本上需要确保正确的字符串编码。例如。您提供给 django 的字符串不是 UTF-8 编码的,因此无法解析某些字符。

    可以在此处找到有关如何查找所请求页面的编码的一些有用建议:urllib2 read to Unicode

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      相关资源
      最近更新 更多