Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python编码中的mysql_Python_Mysql_Encoding_Mysql Python - Fatal编程技术网

python编码中的mysql

python编码中的mysql,python,mysql,encoding,mysql-python,Python,Mysql,Encoding,Mysql Python,这篇文章和我的问题一样,只是想澄清一下 我试图将字符串保存到MySQL数据库,但出现错误: 文件“.smart.py”,第51行,在 (数字、文本、“智能”、“u”) UnicodeDecodeError:“ascii”编解码器无法解码位置中的字节0xc2 25:序号不在范围内(128) 字符串保存在m['Text'] 拉拉*=#和%@?!:;-'“/()” 下面是代码的一个片段 risk = m['Text'] msg = risk.encode('utf8') text = db.escap

这篇文章和我的问题一样,只是想澄清一下

我试图将字符串保存到MySQL数据库,但出现错误:

文件“.smart.py”,第51行,在 (数字、文本、“智能”、“u”)

UnicodeDecodeError:“ascii”编解码器无法解码位置中的字节0xc2 25:序号不在范围内(128)

字符串保存在m['Text']

拉拉*=#和%@?!:;-'“/()”

下面是代码的一个片段

risk = m['Text']
msg = risk.encode('utf8')
text = db.escape_string(msg)

sql = "INSERT INTO posts(nmbr, \
       msg, tel, sts) \
       VALUES ('%s', '%s', '%s', '%s')" % \
       (number, text, 'smart', 'u')
如果我试着注释掉SQL查询并输入打印文本,它会打印出Lala*=#&%@?!:-“/”

只有在处理SQL时才会遇到此错误

MySQL编码设置为utf8\U unicode\U ci。(或者我应该改变这个?)


谢谢。

添加这些参数
MySQLdb.connect(…,使用_unicode=1,charset=“utf8”)

创建光标

cur = db.cursor()
然后像这样执行:

risk = m['Text']
sql = """INSERT INTO posts(nmbr, msg, tel, sts) \
         VALUES (%s, %s, %s, %s)"""
values = (number, risk, 'smart', 'u')
cur.execute(sql,values)  #use comma to separate sql and values, this will ensure values are escaped/sanitized
cur.commit()
现在您不需要这两行:

msg = risk.encode('utf8')
text = db.escape_string(msg)

不清楚您的
m['Text']
值的类型是
StringType
还是
UnicodeType
。我打赌它是一个字节字符串(
StringType
)。如果这是真的,那么在插入之前添加一行
m['Text']=m['Text']。解码('UTF-8')

我得到了上述错误。我想我得到了一个编码错误。如果我只做risk=m['Text']msg=risk.encode('utf8')Text=db.escape_string(msg)打印文本,一切正常。你在使用MySQLdb吗,如果是,你的连接字符串是什么?db=MySQLdb.connect(“localhost”,“root”,“password”,“application”)mysql\u异常。编程错误:(1064,'您的SQL语法有错误;请检查与您的MySQL服务器版本相对应的手册,以了解可在“\\'”、“\'Lala*=”和%@”附近使用的正确语法:;-“\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\(我已经删除了围绕%s的撇号)我打印出数组m,文本是:“text”:u'Lala*=#和%@@@u?!:;-\'“/()\ xa5\xa1\xbf”