2009-11-27 65 views
3
_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将它保存到数据库中。INSERT进入MySQL时出现错误

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

编辑:好像我必须将数据库设置为UTF-8?什么是这样做的命令?

+0

您在哪里执行查询的代码... – Bobby 2009-11-27 12:25:05

+0

Bobby,查询是new_u,new_u.save()。这是Django查询 – TIMEX 2009-11-27 12:25:38

+0

@alex:哦......从来没有与该系统工作。可能最好的猜测是,你不会逃避html-String,他试图插入'错误'的值。对于PHP的功能称为mysql_real_escape_string。 – Bobby 2009-11-27 12:27:46

回答

3

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

如何找到所请求的页面编码一些有用的建议,可以在这里找到:urllib2 read to Unicode

0

有2种方式去,如果你想改变的字符在MySQL设置。 首先是数据库的默认值,参见MySQL Alter database, ,第二个是每个表:MySQL Alter Table

数据库为默认字符集,我相信,新表。这个 可以基于每个表格进行覆盖,因为您已经有 表格,所以您需要执行此操作。 “utf8”是一个受支持的字符集。

也看看Blog about UTF8 with django and MySQL