sqlite 3 attribute error __exit__

Sayth Renshaw flebber.crue at gmail.com
Sun May 15 23:40:59 EDT 2016


> 
> As you've written it, the statement declares your intent to enter both
> ‘conn’ and ‘conn.cursor()’ as context managers.
> 
>     <URL:https://docs.python.org/3/reference/compound_stmts.html#with>
> 
> To “enter a context manager” entails calling the ‘__enter__’ method on
> the context manager object. So that will happen to both ‘conn’ and
> ‘conn.cursor()’.
> 
> Are both of those objects context managers? If not, you will get the
> error that you reported.
> 

I actually am unsure about context managers. I was talking to ChrisA the other day and using psycog2 this code worked.

conn = psycopg2.connect("")
with conn, conn.cursor() as cur:
        # First, create tables.
    cur.execute("drop table if exists meetings, races, horses")
    cur.execute("create table meetings (" +
                ", ".join("%s varchar" % fld for fld in meetattrs)
                + ")")
    cur.execute("create table races (" +
                ", ".join("%s varchar" % fld for fld in raceattrs)
                + ")")
    cur.execute("create table horses (" +
                ", ".join("%s varchar" % fld for fld in horseattrs)
                + ")")

I tried to change it to sqlite3 and it fails. I thought it may have been sqlite specific.

Found this http://initd.org/psycopg/articles/2013/04/07/psycopg-25-released/ I found using a context managers search and psycopg2 provides this as a feature.

from the site.

Connections and cursors as context managers

A recent DBAPI extension has standardized the use of connections and cursors as context managers: it is now possible to use an idiom such as:

with psycopg2.connect(DSN) as conn:
    with conn.cursor() as curs:
       curs.execute(SQL)

with the intuitive behaviour: when the cursor block exits the cursor is closed; when the connection block exits normally the current transaction is committed, if it exits with an exception instead the transaction is rolled back, in either case the connection is ready to be used again (FIXED: the connection is NOT closed as originally stated).

thanks

Sayth






More information about the Python-list mailing list