python3.6 cx_oracle连接数据库报编码错UnicodeDecodeError

2024-12-03 22:15:28
推荐回答(3个)
回答1:

我说下我遇到的情况

数据库字符集是 ZHS16GBK

错误的情况是

UnicodeDecodeError: 'gbk' codec can't decode byte 0xa7 in position 12: illegal multibyte sequence

经过检查,在fetchall()获取记录时,查询到的记录里面有乱码(应该是不包含在数据库现有字符集下的字符)

临时的一个解决办法是

db=cx_Oracle.connect(dblink,encoding='UTF-8')

这样可以读取了,读取到的内容为

广州市同泰路

其中 ''应该是之前不可被读取的字符,希望对各位有帮助

回答2:

python3.6 cx_oracle连接数据库报编码错UnicodeDecodeError
# -*- coding:utf-8 -*-
#!/usr/bin/env python
'''
Created on 2014年8月4日

@author: 188007

连接Oracle数据库的class
'''
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.ZHS16GBK'
import cx_Oracle
import sys

class Oracle:
'''
python access oracle helper tool class
'''

def __init__(self, ip,port,db,user,pwd):
self.ip = ip
self.port = port
self.db = db
self.user = user
self.pwd = pwd

def __GetConnect(self):
""" 得到连接信息 返回: conn.cursor() """
if not self.db:
raise(NameError,"没有设置数据库信息")
dsn=cx_Oracle.makedsn(self.ip,self.port,self.db)
self.conn=cx_Oracle.connect(self.user,self.pwd,dsn)
cur = self.conn.cursor()
if not cur:
raise(NameError,"连接数据库失败")
else:
return cur

def ExecQuery(self,sql):
""" 执行查询语句 返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
调用示例:
oracle = Oracle('10.27.95.253','1561','GFDMS','GFITAPPS','GFITAPPS')
resList = oracle.ExecQuery("SELECT OBJID,NUMCODE,AREACODE,AREANAME,PROVCODE,PROVNAME,CITYCODE,CITYNAME,TOWNCODE,TOWNNAME,REMARK FROM GFDMS.THZONE ORDER BY NUMCODE")
for (AREANAME) in resList:
print str(AREANAME).decode('gb2312')
"""
try:
cur = self.__GetConnect()
cur.execute(sql)
resList = cur.fetchall()

#查询完毕后必须关闭连接
self.conn.close()
except Exception, err:
sys.exit(1)

return resList

def ExecNonQuery(self,sql):
""" 执行非查询语句
调用示例:
oracle.ExecNonQuery("insert into THZONE values('x','y')")
"""
try:
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
except Exception, err:
sys.exit(1)

# def main():
# # oracle = Oracle('10.27.95.253','1561','GFDMS','GFITAPPS','GFITAPPS')
# # #返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
# # oracle.ExecNonQuery("insert into THZONE values('x','y')")
# oracle = Oracle('10.27.95.253','1561','GTEST','GTAPPS','GTAPPS')
# resList = oracle.ExecQuery("SELECT OBJID,NUMCODE,AREACODE,AREANAME,PROVCODE,PROVNAME,CITYCODE,CITYNAME,TOWNCODE,TOWNNAME,REMARK FROM GTEST.THZONE ORDER BY NUMCODE")
# for (AREANAME) in resList:
# print str(AREANAME).decode('utf-8')
#
# if __name__ == '__main__':
# main()

回答3:

您这个问题解决了没?怎么解决的?能教教我吗?