我想序列化查询结果。这是我的例子:
_pickle.PicklingError: Can't pickle <class 'pypyodbc.TupleRow.<locals>.Row'>:
attribute lookup Row on pypyodbc failed
它会产生以下错误:
select state
from customers
group by state
having count(*) = (select min(cnt)
from (select count(*) from customers group by state) s
);
我认为pickle并不完全支持pypyodbc对象。什么是解决方法?
答案 0 :(得分:2)
我能够使用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()