我试图弄清楚如何使用 Python 3 中的 SQLAlchemy 将许多(大约 100k)记录插入到数据库中。一切都指向使用事务。但是,我对如何完成感到有些困惑。
有些页面声明您从 获得交易connection.begin()
,其他地方说它是,这里session.begin()
的这个页面说它是不存在的。session.create_transaction()
这是我正在尝试做的事情:
def addToTable(listOfRows):
engine = create_engine('postgresql+pypostgresql:///%s' % db,echo = False)
Session = sessionmaker(bind = engine)
session = Session()
table = myTable(engine,session)
for row in listOfRows:
table.add(row)
table.flush() ### ideally there would be a counter and you flush after a couple of thousand records
class myTable:
def __init__(self,engine,session):
self.engine = engine
self.session = session
self.transaction =createTransaction()# Create transaction code here
def add(self,row):
newRow = tableRow(row) ## This just creates a representation of a row in the DB
self.transaction.add(newRow)
self.transaction.flush()
def flush(self):
self.transaction.commit()