2012-03-17 33 views
3

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'

+0

我没有你的答案,但+1只是为了这个名字。 :) – 2012-03-17 03:53:17

+0

如果adodbapi没有此功能切换,您将不得不编辑/猴子修补它。错误在于堆栈跟踪显示,在adodbapi.py的第651行,他们试图调用一个Unicode字符串的'str'... – Borealid 2012-03-17 03:55:17

+0

@Borealid - 我想这可能是因为我正在运行python脚本从'cmd.exe'窗口中。这可能不是unicode能力。 – Cheeso 2012-03-17 03:57:51

回答

1

我能拿到剧本完成运行,打印所有检索到的行,通过修改输出部分要做到这一点:

# show the result 
result = cur.fetchall() 
for item in result: 
    print repr(item) 

,而不是这样的:

# show the result 
result = cur.fetchall() 
for item in result: 
    print item 

所以这个问题实际上是在adodbapi中使用str,正如Borealid在评论中所说。但这并不一定是阻塞问题。通常,当从数据库查询中检索行时,人们不仅仅需要一行的字符串表示;他们想要检索单个列中的值。我的结论是,由于我构建测试应用程序的方式,这个问题是一个人为问题。

0

我怎么能告诉它只是使用UTF-8?

chcp 65001