执行查询时PyODBC Python3错误(Ubuntu 14.04)

2024-09-30 10:40:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python3.4.3在ubuntu14.04上配置ODBC。我可以成功建立连接,但在执行时出现此错误:

>>> cursor.execute("SELECT * FROM xxx.yyy.zzz LIMIT 100;")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
pyodbc.ProgrammingError: ('42000', '[42000] ERROR:  \'S\'\nerror    ^ found "S" (at char 1) expecting a keyword (27) (SQLExecDirectW)')

执行查询的相同代码在Python2.7上运行良好。我还能够使用strace isql从unixshell建立连接,这使我认为我的ODBC连接工作正常。是吗?


关于这一点,网上没有太多信息。以下是我根据我发现的一些博客所做的一些事情。我的理解正确吗?

  1. PyODBC ticket所述:

    In my case the ODBC driver (NetezzaSQL) was set to use UTF8. I first though the issue was either a UC2 or UC4 build of Python. Both made no difference. Switching the driver to UTF16 (UnicodeTranslationOption=utf16) fixed the issue for me.

    我在所有的obdc*.ini文件中都设置了UnicodeTranslationOption=utf16因为我的代码是在Python2.7上运行的,这是否意味着这个参数设置正确?

  2. document to configure PyODBC中提到我应该用UCS2版本来构建Python。但是在我的机器上,Python2.7和{}都说他们有UCS4版本,而且由于代码是在python2.x上运行的,这意味着{}不是这里的问题。在

    我使用以下命令检查了UCF版本:

    user@host:~$ python -c "import sys;print(sys.maxunicode<66000 and'UCS2'or'UCS4')"
    UCS4
    user@host:~$ python3 -c "import sys;print(sys.maxunicode<66000 and'UCS2'or'UCS4')"
    UCS4
    

Tags: ortheto代码版本driversysissue
2条回答

必须强制pyodbc连接使用UTF-8。(在这张纸条上,留下odbcinst.ini文件具有“UnicodeTranslationOption=utf8”设置的文件)

创建连接后,请在使用前执行以下操作:

connection.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8')
connection.setdecoding(pyodbc.SQL_WCHAR, encoding='utf-8')
connection.setdecoding(pyodbc.SQL_WMETADATA, encoding='utf-8')
connection.setencoding(encoding='utf-8')

我也有同样的问题,这是唯一对我有效的方法。更多信息可以在github上的pyodbc文档中找到:https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-Netezza

/etc/odbcinst.ini文件中,将UnicodeTranslationOption设置为utf16

UnicodeTranslationOption = utf16

然后将/etc/odbcinst.ini复制到/home/<user>/.odbcinst.ini

另一个技巧是将/etc/odbc.ini复制到/home/<user>/.odbc.ini,这样就不需要导出以下变量:

  • LD_LIBRARY_PATH
  • ODBC_INI
  • NZ_ODBC_INI_PATH

相关问题 更多 >

    热门问题