This is an example of using pandas to read data from sqlite.
from sqlalchemy import create_engine
import pandas aspd
engine=create_engine('sqlite://:memory:')
with engine.connect() as conn, conn.begin():
data=pd.read_sql_table('data',conn)
I know the basic usage of the with statement, but I have never seen a function call after as.I would appreciate it if you could tell me the role of conn.begin().
python sql sqlalchemy
It's not that difficult, it's just that there's no as
on the back, equivalent to the following.
(.begin()
is the beginning of the transaction.)
with engine.connect() as conn:
with conn.begin():
pass# Something to be done
You can also do these things
with engine.begin() as conn:
pass# Something to be done
Note: (docs.sqlalchemy.org) Working with Engines and Connections:Using Transactions
Multiple context managers can be used in With statements.They act as if they were nested.
When multiple elements exist, the context manager proceeds as if multiple with statements were nested:
with A() as a, B() as b:
SUITE
This is equivalent to:
with A() as a:
with B() as b:
SUITE
Interviewer: with statement
The code for the question is the omission of asb
in the example above.In other words,
with engine.connect() as conn:
with conn.begin():
will be
© 2024 OneMinuteCode. All rights reserved.