[CentralOH] Context Manager for Database Connection
jep200404 at columbus.rr.com
jep200404 at columbus.rr.com
Wed Nov 13 22:08:41 CET 2013
How would you improve the following context manager for
a database connection?
import mysql.connector
...
class DBOpen:
def __init__(self, config):
self.config = config.copy()
def __enter__(self):
self.cnx = mysql.connector.Connect(**self.config)
return self.cnx
def __exit__(self, exc_type, exc_value, exc_tb):
self.cnx.close()
...
with DBOpen(connection_config) as cnx:
do_something(student_id)
The full code is attached in a tarball.
Sample output using an actual database[1] follows.
(env)test at test:~/mysql$ python foo.py 3
6
(3, 1, 20)
(3, 2, 13)
(3, 3, 69)
(3, 4, 17)
(3, 5, 11)
(3, 6, 94)
(env)test at test:~/mysql$
If that's not a good question, feel free to correct it.
Also feel free to correct how other things are done in the code.
[1] for 2nd edition of Paul DuBois's "MySQL"
http://www.kitebird.com/mysql-book/sampdb-2ed/sampdb.tar.gz
-------------- next part --------------
A non-text attachment was scrubbed...
Name: tx.tgz
Type: application/x-gzip
Size: 819 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/centraloh/attachments/20131113/632a3f9d/attachment.bin>
More information about the CentralOH
mailing list