I am trying to figure out how to insert many (in the order of 100k) records into a database using SQLAlchemy in Python 3. Everything points to using transactions. However, I am slightly confused as to how that is done.
Some pages state that you get a transaction from connection.begin(), others places say it is session.begin() and this page here says it is session.create_transaction() which doesn't exist.
Here is what I am trying to do:
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()