gpt4 book ai didi

python - Pickle 和 pypyodbc 光标

转载 作者:行者123 更新时间:2023-12-01 04:23:06 26 4
gpt4 key购买 nike

我想序列化查询结果。这是我的例子:

import pypyodbc
import pickle

connection_string ='Driver={SQL Server Native Client 11.0};Server=localhost;' \
'Database=someDB;Uid=someLogin;Pwd=somePassword;'
connection = pypyodbc.connect(connection_string)
sql_query = "SELECT * FROM SomeTable"
cur = connection.cursor()
cur.execute(sql_query)
query_list = list(cur)

with open(r'D:\query_result', 'wb') as f:
pickle.dump(query_list, f)
cur.close()
connection.close()

它会生成以下错误:

_pickle.PicklingError: Can't pickle <class 'pypyodbc.TupleRow.<locals>.Row'>: 
attribute lookup Row on pypyodbc failed

我猜pickle不完全支持pypyodbc对象。解决方法是什么?

最佳答案

我能够使用 pypyodbc 重新创建问题,而相同的代码似乎可以在 pyodbc 上正常工作。 pypyodbc 的一种可能的解决方法可能是将结果转换为字典对象列表,然后将其序列化:

import pickle, pypyodbc
connection_string = (
r"Driver={SQL Server Native Client 10.0};"
r"Server=(local)\SQLEXPRESS;"
r"Database=myDb;"
r"Trusted_connection=yes;"
)
connection = pypyodbc.connect(connection_string)
cur = connection.cursor()
cur.execute("SELECT * FROM Donors")

column_names = [x[0] for x in cur.description]
query_list = [dict(zip(column_names, row)) for row in cur.fetchall()]

with open(r'C:\Users\Gord\Desktop\query_result', 'wb') as f:
pickle.dump(query_list, f)
cur.close()
connection.close()

关于python - Pickle 和 pypyodbc 光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33467085/

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