为什么使用 pyodbc 访问大于 511 的字符字段时 count() return 0?

Why does count() return 0 when accessing a character field larger than 511 using pyodbc?

我试图计算数据库字符字段中子字符串的出现次数(PostgreSQL、pyodbc、Python 3.4.4、Windows 7)。但是当字符字段大于 511 时,count() 总是返回零。只有在返回字符串 "doing something" 之后(例如访问索引 0 处的字符串或使用 print() 查看字符串),count() 才返回预期值。长度为 511 或更短的字符串没有问题。

此外(512 或更大)字符串的大小似乎发生了变化,请参见下面的示例。

使用 pyodbc 时,PostgreSQL、SQLite 和 Oracle 似乎会出现此问题。我无法使用 psycopg2 重现它。

所以,这是 pyodbc 中的错误吗?还是某种优化而 count() 确实有问题? (其他函数似乎没问题,例如len()。)

以下 Python 脚本将使用 PostgreSQL、SQLite-ODBC 或 Oracle 重现此问题。 它将创建两个表,插入文本并尝试对返回的数据使用函数 count()。

import pyodbc
import sys

#conn   = pyodbc.connect('driver={SQLite3 ODBC Driver}; server=localhost; database=D:\test.db;')
#conn   = pyodbc.connect('DSN=test-oracle;uid=xx;pwd=xx')
conn   = pyodbc.connect('DSN=test-postgresql;uid=xx;pwd=xx')
cursor = conn.cursor()
with conn.cursor() as cursor:

    cursor.execute("create table testtable511 (txt char(511) default ' ' primary key not NULL);")
    cursor.execute("insert into testtable511 (txt) values ('"+511*"t"+"');")
    cursor.execute("create table testtable512 (txt char(512) default ' ' primary key not NULL);")
    cursor.execute("insert into testtable512 (txt) values ('"+512*"t"+"');")

    cursor.execute('select * from testtable511')
    data511  = cursor.fetchone()
    print('511')
    print(80*'#')
    # count is 511, size is 560
    print('counting t before "accessing" string of testtable511:     ', data511[0].count('t'))
    print('size of string before "accessing" string of testtable511: ', sys.getsizeof( data511[0] ))
    data511[0][0]
    # count is 511, size is 560
    print('counting t after "accessing" string of testtable511:      ',  data511[0].count('t'))
    print('size of string after "accessing" string of testtable511:  ',  sys.getsizeof( data511[0] ))
    print(80*'#')

    print()

    cursor.execute('select * from testtable512')
    data512 = cursor.fetchone()
    print('512')
    print(80*'#')
    # count is 0, size is 1106
    print('counting t before "accessing" string of testtable512:     ', data512[0].count('t'))
    print('size of string before "accessing" string of testtable512: ', sys.getsizeof( data512[0] ))
    data512[0][0]
    # count is 512, size is 593
    print('counting t after "accessing" string of testtable512:      ', data512[0].count('t'))
    print('size of string after "accessing" string of testtable512:  ', sys.getsizeof( data512[0] ))
    print(80*'#')

    cursor.execute("drop table testtable511;")
    cursor.execute("drop table testtable512;")

conn.close()

更新:问题出在 pyodbc 3.0.10 上。版本 4.0.11 修复了这个问题。

问题已在 pyodbc 4.0.11 中修复。

所以这似乎是早期 pyodbc 版本的错误(我使用的是 3.0.10)。