使用pymssql模块导出到CSV失败并显示UnicodeEncodeError

时间:2014-08-26 16:32:06

标签: python-2.7 pymssql

我正在尝试执行一个简单的sql并将结果写入CSV输出。但是,代码失败了:

<pymssql.Connection object at 0x01EF4AF8>
<_csv.writer object at 0x0B6C3270>
 Traceback (most recent call last):
  File "C:\_WORKSPACE\ReportsInventory\CustomReports\CustomReports.py", line 38, in     <module>
f.writerow(row)
 UnicodeEncodeError: 'ascii' codec can't encode character u'\x96' in position 14: ordinal not in range(128)

我正在运行的数据库是:MSSQLSERVER。我在连接字符串中指定了charset =“ISO-8859-1”。我知道这是一个特殊的角色,但是如何处理它们以便插入可以成功?

提前致谢, 西马克

我的完整代码如下:

import pymssql
import csv

import datetime 
import re
import sys
from config import config

user=r'user'
database = config['ProdDatabase']
connection = pymssql.connect(config['ProdHost'], user, config['ProdPassword'],    database,charset="ISO-8859-1")
connLog = pymssql.connect(config['ProdHost'], user, config['ProdPassword']
print connection

cursor = connection.cursor()

query = """ SELECT dbname,ReportType,ReportID,Report,ReportDriver,FilteredColumn,Filter,FilteredConditionValue     from tempReports """

cursor.execute(query)


data=cursor.fetchall()

f =    csv.writer(open("C:\\_WORKSPACE\\ReportsInventory\\CustomReports\\customreports.csv","w"))
print f
for row in data:
    f.writerow(row)
cursor.close()
f.close()
connection.close()

1 个答案:

答案 0 :(得分:0)

data=cursor.fetchall()

# encode characters
data =[c.encode('ascii','ignore') for c in data]

f = csv.writer(open("C:\\_WORKSPACE\\ReportsInventory\\CustomReports\\customreports.csv","w"))
print f
for row in data:
    f.writerow(row)
cursor.close()
f.close()
connection.close()