这里是Python新手。
我在Windows7上使用python2.7.2。
我已经安装了PyWin32扩展(build 217)。
我在c:\Python27\Lib\site-packages\adodbapi中安装了
我有一个非常简单的模块,用于查询module中的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)...which非常没有帮助。对我来说。
我猜想adodbapi正试图将u‘\xe9 9’字符编码到ASCII中。我明白为什么会失败。我想它是作为print语句的一部分来尝试这样做的。
为什么要把这个字符编码成ASCII呢?
我怎么才能告诉它只用UTF-8?
ps:我正在从的cmd.exe提示符中运行脚本。这是否意味着stdout总是ASCII?
eg,\python27\python.exe -c "import sys; print(sys.stdout.encoding)"
给我“cp437”
发布于 2012-03-17 17:33:37
我能够通过修改输出部分来完成脚本的运行,打印所有检索到的行:
# 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因此,正如博拉利德在一篇评论中所说,问题实际上是在阿多巴里使用str。但这不一定是一个阻塞问题。通常,当从数据库查询中检索行时,人们不只是想要行的字符串表示;他们希望检索各个列中的值。我的结论是,这个问题是一个人为的问题,因为我是建立一个测试应用程序的方式。
发布于 2012-03-17 04:43:55
我怎么才能告诉它只使用UTF-8?
chcp 65001https://stackoverflow.com/questions/9747090
复制相似问题