2

这对我来说是一个长期存在的问题。我有一个无法更改的专有数据库,并且许多表都有定义为例如十进制(12、4)的字段。

当我尝试像这样使用 pyodbc/freeTDS 从 ubuntu 12.04 上的此类表中提取数据时...

import pyodbc
connection_string = 'DRIVER={FreeTDS};DSN=<myDSN>;UID=<my_user>;PWD=<my_password>;'
conn = pyodbc.connect(connection_string)
cur = conn.cursor()
cur.execute('SELECT myfield FROM mytable')
for row in cur.fetchall():
    print row[0]

...我收到一个非常无益的消息。

Traceback (most recent call last):   File
"/path/to/testing_pyodbc.py", line 6, in <module>
    for row in cur.fetchall(): pyodbc.Error: ('HY000', 'The driver did not supply an error!')

而如果我将结果转换为浮点数,则查询运行没有问题。

import pyodbc
connection_string = 'DRIVER={FreeTDS};DSN=<myDSN>;UID=<my_user>;PWD=<my_password>;'
conn = pyodbc.connect(connection_string)
cur = conn.cursor()
cur.execute('SELECT CAST(myfield AS FLOAT) FROM mytable')
for row in cur.fetchall():
    print row[0]

我的第一个问题是我可以在不更改表结构的情况下解决这个问题吗?该数据库不是我的,所以我无权更改它。

我想使用 SQLAlachemy 从数据库中获取这些数据。我在这样的 Windows 上做得很开心。

class MyTable(Base):
    __tablename__ = u'table'
    ...
    myfield = Column(DECIMAL(12, 4), nullable=True)
    another_field = Column(DECIMAL(12, 4), nullable=True)
    ...

我的第二个问题(如果第一个问题无法解决)是我可以定义我的 sqlAlchemy 类以自动将数据转换为引擎盖下的浮点数,这样使用该类的代码就不必担心了吗?

我正在运行 ubuntu 12.04,所以安装的 freetds 版本是 0.91:

$ dpkg -s freetds-common
Package: freetds-common
Status: install ok installed
Multi-Arch: foreign
Priority: optional
Section: libs
Installed-Size: 91
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Architecture: all
Source: freetds
Version: 0.91-1
Replaces: libct3, libct4 (<< 0.82-1)
Description: configuration files for FreeTDS SQL client libraries
 FreeTDS is an implementation of the Tabular DataStream protocol, used for
 connecting to MS SQL and Sybase servers over TCP/IP.
 .
 This package manages the configuration files that are common to all of
 the TDS client library implementations (CT-Lib, DB-Lib, and ODBC),
 stored in /etc/freetds/.
Original-Maintainer: Steve Langasek <vorlon@debian.org>
Homepage: http://www.freetds.org/

但是当我问 tsql 时,它告诉我 v0.64:

$ tsql -C
Compile-time settings (established with the "configure" script):
                           Version: freetds v0.64
    MS db-lib source compatibility: no
       Sybase binary compatibility: unknown
                     Thread safety: yes
                     iconv library: yes
                       TDS version: 5.0
                             iODBC: no
                          unixodbc: yes

另请注意,当我在命令行上使用 tsql 或 isql 时,他们很乐意在没有 CAST() 操作的情况下给我数据。

4

0 回答 0