osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python/SQLite best practices


On Mon, Aug 05, 2019 at 01:49:24PM -0400, Dave via Python-list wrote:

> * Passing connections and cursors - good, bad indifferent?  I try to avoid
> passing file handles unless necessary, so I view connections and cursors the
> same.

Connections may be more long-lived, per thread perhaps.

Cursors would generally be throw-away.

Transactions involving several commands may require passing
around of connections and/or cursors, however.


> Best way to establish the connection and cursor, as well as close them? I
> have seen many ways to do this, and know that the with block can be used to
> create a connection and close it automatically, but the same is not true of
> the cursor.  Also, using only a with block does not handle any errors as
> well as a try/with.  For example:
>
>     |   try:
>     |	    # Use with block to create connection ? it will close self.
>     |       with sqlite3.connect(path) as conn:
>     |           cur = conn.cursor()
>     |           cur.execute(sql_ProjectsTable)
>     |           cur.close()
>     |   except Error as e:
>     |       print(e)

Use of

	try:
	except:
	finally:

may come in handy for clean closure.

Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B