PyODBC查询

时间:2017-08-31 12:04:19

标签: python sql-server unicode pyodbc

我在使用PyODBC查询我的MSSQL服务器时遇到了麻烦。

我相信的原因是我有使用unicode命名的列。这些列来自于在我的主数据中旋转单个列。

有问题的专栏是“afkastningsgrad_primær_drift”

知道如何运行此查询吗? (由于我缺乏服务器所有权,在服务器上构建视图并重命名列不是一个选项)

SQL:

WITH dataTable AS (
    SELECT 
        KredsEjdNr, Navn, Vaerdi
    FROM qryEjendomsData

    WHERE 
        RegnskabsAar = 2016 
        AND Projekt = 1710
        AND Navn IN (
            'ekm_ko' , 'afkastningsgrad_primær_drift', 'fremst_pris_maelk'
        )
    GROUP BY KredsEjdNr, Navn, Vaerdi
), 
pivotData AS (

    SELECT * 
    FROM dataTable
    PIVOT
        (
            SUM(Vaerdi)
            FOR[Navn] IN (
                [ekm_ko], [afkastningsgrad_primær_drift], [fremst_pris_maelk]
            )
        )
    AS pivotTable
)

SELECT 
    CAST([KredsEjdNr] AS NVARCHAR) AS [kredsEjdNr], 
    CAST(ekm_ko AS int) AS [EKM pr ko],
    [afkastningsgrad_primær_drift] as [Afkastningsgrad],
    [fremst_pris_maelk] AS [Fremstillingspris pr. kg EKM]
 from pivotData
 where [ekm_ko] IS NOT NULL and [fremst_pris_maelk] IS NOT NULL
 order by kredsEjdNr

Python代码:

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
connectionstring = 'DRIVER={SQL Server Native Client 11.0};SERVER=server;DATABASE=database;UID=%s;PWD=%s' %(usr,pswd)
conn = pyodbc.connect(connectionstring)
cursor = conn.cursor()
dataList = cursor.execute(unicode(sql)).fetchall()

错误:

  

回溯(最近一次调用最后一次):文件“data.py”,第84行,在          dataList = cursor.execute(unicode(sql))。fetchall()UnicodeDecodeError:'ascii'编解码器无法解码字节0xc3的位置   183:序数不在范围内(128)

1 个答案:

答案 0 :(得分:2)

问题不在于列名中的Unicode字符,而是在Python2下的str变量中使用非ASCII 字节。当pyodbc .execute调用将命令文本作为str接收时,它会尝试使用默认编码处理它,该编码是' ascii'对于Python2。

以下测试代码

# -*- coding: utf-8 -*-
import sys
print("sys.getdefaultencoding() is '{0}'".format(sys.getdefaultencoding()))
import pyodbc

cnxn = pyodbc.connect("DSN=SQLmyDb", autocommit=True)
crsr = cnxn.cursor()

# setup test environment
crsr.execute(u"CREATE TABLE #tmp (afkastningsgrad_primær_drift INT)")
crsr.execute(u"INSERT INTO #tmp VALUES (1)")

print('')
print('Test_1: "SELECT * ..." as str')
sql = "SELECT * FROM #tmp"
print("  sql: " + repr(sql))
crsr.execute(sql)
print("    column name from result set: " + repr(crsr.description[0][0]))

print('')
print('Test_2: "SELECT colname ..." as str')
sql = "SELECT afkastningsgrad_primær_drift FROM #tmp"
print("  sql: " + repr(sql))
try:
    crsr.execute(sql)
    print("    OK")
except UnicodeDecodeError as ude:
    print("    UnicodeDecodeError: " + str(ude))

print('')
print('Test_3: "SELECT colname ..." as unicode')
sql = sql.decode('utf-8')
print("  sql: " + repr(sql))
try:
    crsr.execute(sql)
    print("    OK")
except Exception as ex:
    print("    Exception: " + str(ex))

cnxn.close()

产生

sys.getdefaultencoding() is 'ascii'

Test_1: "SELECT * ..." as str
  sql: 'SELECT * FROM #tmp'
    column name from result set: u'afkastningsgrad_prim\xe6r_drift'

Test_2: "SELECT colname ..." as str
  sql: 'SELECT afkastningsgrad_prim\xc3\xa6r_drift FROM #tmp'
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 27: ordinal not in range(128)

Test_3: "SELECT colname ..." as unicode
  sql: u'SELECT afkastningsgrad_prim\xe6r_drift FROM #tmp'
    OK

Test_1显示具有Unicode字符的列名称正确返回为unicode对象。

Test_2显示默认的Python2编码(' ascii')在str上阻塞,其中包含大于0x7F的UTF-8字节。

Test_3表明如果我们使用.decodestr(包含UTF-8字节)转换为正确的unicode对象然后传递给{{1},则不会发生错误方法。