解决python读取sqlserver数据库乱码问题
·
这个问题困扰了我一天,晚上11点多终于解决
代码如下
import pymssql
pd.set_option('display.max_column', None)
com = pymssql.connect(server='host', user='user', password='password', database='database', charset='utf8')
cursor = com.cursor()
cursor.execute("SELECT name FROM SysObjects Where XType='U' and name like 'u_ware' ORDER BY Name")
tables = cursor.fetchall()
print(tables)
sql = f"""select warename,wareid,barcode,convert(nvarchar(20), warespec) warespecb,convert(nvarchar(20), producer) producer,advsaleprice from {table[0]}""" # 重点是这个comvert函数,要把乱码列转成nvarchar类型
cursor.execute(sql)
res = cursor.fetchall()
col = [i[0] for i in cursor.description]
print(col)
df = pd.DataFrame(res, columns=col)
print(df)
下面是我试过的方法
我是把表格用pymssql读取出来,再编码
df1 = df.apply(lambda x: x['warename'].encode('cp936').decode('gb2312'), axis=1)
这里编码encode,解码decode,试尽了各种字符集,都没有用
这个问题终于解决,能睡个好觉了
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐


所有评论(0)