使用python查询mysql:当查询条件为汉字时,应该使用什么编码和解码
首先,下面是我的mysql服务器编码配置: 服务器1:使用python查询mysql:当查询条件为汉字时,应该使用什么编码和解码,python,mysql,encoding,utf-8,decode,Python,Mysql,Encoding,Utf 8,Decode,首先,下面是我的mysql服务器编码配置: 服务器1: 1 character_set_client utf8 2 character_set_connection utf8 3 character_set_database utf8 4 character_set_filesystem binary 5 character_set_results utf8 6 character_set_server utf8 7 character_
1 character_set_client utf8
2 character_set_connection utf8
3 character_set_database utf8
4 character_set_filesystem binary
5 character_set_results utf8
6 character_set_server utf8
7 character_set_system utf8
我正在尝试使用python连接到这个mysql数据库,并使用中文查询条件查询一些数据
此数据库中的某些数据示例如下所示:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
conn = MySQLdb.connect(host="1.1.1.1.",user="online",passwd="hdhjjdd",port=3406,db="data_platform")
cursor = conn.cursor()
name = "赵胜".decode("utf-8")
sql="select user_name, call_params from tb_user_log where user_name='%s' order by user_name desc" %(name.encode("utf-8"))
count = cursor.execute(sql)
print count #always 0 ,cannot query out any data
#执行SQL,创建一个数据库.
我的sampale python代码如下所示:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
conn = MySQLdb.connect(host="1.1.1.1.",user="online",passwd="hdhjjdd",port=3406,db="data_platform")
cursor = conn.cursor()
name = "赵胜".decode("utf-8")
sql="select user_name, call_params from tb_user_log where user_name='%s' order by user_name desc" %(name.encode("utf-8"))
count = cursor.execute(sql)
print count #always 0 ,cannot query out any data
#执行SQL,创建一个数据库.
这个查询无法查询出任何数据,我想是编码问题,因为是在线数据库,所以我无法更改mysql服务器的编码配置。因此,我不知道如何修改python代码以使中文查询条件工作
有人能帮我吗?
“赵胜".解码(“utf-8”)
错误,返回AttributeError:'str'对象没有属性“decode”
,而“赵胜“.encode(“utf-8”)
返回字节序列b'\xe8\xb5\xb5\xe8\x83\x9c'
这是正确的十六进制。但我认为您不需要encode()
或解码()
。请提供显示创建表
。