gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:09:48 24 4
gpt4 key购买 nike

我试图计算一个子字符串在数据库(PostgreSQL、pyodbc、Python 3.4.4、Windows 7)的字符字段中出现的次数。但是当字符字段大于 511 时,count() 总是返回零。只有在对返回的字符串“做某事”之后(例如访问索引 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)。

关于python - 为什么使用pyodbc访问大于511的字符字段时count()返回0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42369502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com