1

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

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 对象。什么是解决方法?

4

1 回答 1

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()
于 2015-11-02T02:54:41.437 回答