Python新手在这里。Ye olde UnicodeEncodeError从MS SQL查询打印结果与adodbapi
我在Windows7上使用python2.7.2。
我已经安装了PyWin32扩展(build 217)。
我已经adopdbapi安装在c:\Python27\Lib\site-packages\adodbapi
我有一个非常简单的模块,查询在MS SQL Server中的AdventureWorks2008LT数据库。
import adodbapi
connStr='Provider=SQLOLEDB.1;' \
'Integrated Security=SSPI;' \
'Persist Security Info=False;' \
'Initial Catalog=AVWKS2008LT;' \
'Data Source=.\\SQLEXPRESS'
conn = adodbapi.connect(connStr)
tablename = "[salesLT].[Customer]"
# create a cursor
cur = conn.cursor()
# extract all the data
sql = "select * from %s" % tablename
cur.execute(sql)
# show the result
result = cur.fetchall()
for item in result:
print item
# close the cursor and connection
cur.close()
conn.close()
AdventureWorks2008LT示例数据库包含客户,产品,地址和订单表(等)。这些表中的一些字符串数据是unicode。
查询工作,为第一对夫妇行。我看到了预期的产出。但随后,脚本失败,并显示以下消息:
Traceback (most recent call last):
File "C:\dev\python\query-1.py", line 24, in <module>
print item
File "C:\Python27\lib\site-packages\adodbapi\adodbapi.py", line 651, in __str__
return str(tuple([str(self._getValue(i)) for i in range(len(self.rows.converters))]))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(128)
......这是非常没有帮助的。对我来说。
我收集到adodbapi试图将u'\ xe9'字符编码为ASCII。我明白为什么会失败。 我想它是试图做到这一点,作为print
声明的一部分。
它为什么要将字符编码为ASCII?
我该如何告诉它只使用UTF-8?
ps:我在Windows中运行cmd.exe提示符下的脚本。这是否意味着stdout始终是ASCII?
如\python27\python.exe -c "import sys; print(sys.stdout.encoding)"
给我 'CP437'
我没有你的答案,但+1只是为了这个名字。 :) – 2012-03-17 03:53:17
如果adodbapi没有此功能切换,您将不得不编辑/猴子修补它。错误在于堆栈跟踪显示,在adodbapi.py的第651行,他们试图调用一个Unicode字符串的'str'... – Borealid 2012-03-17 03:55:17
@Borealid - 我想这可能是因为我正在运行python脚本从'cmd.exe'窗口中。这可能不是unicode能力。 – Cheeso 2012-03-17 03:57:51