[Tutor] Good Taste Question: Using SQLite3 in Python
Jugurtha Hadjar
jugurtha.hadjar at gmail.com
Wed Apr 29 05:06:05 CEST 2015
Hello, all..
I have a class with methods that access a database (SQLite3). I have
included an excerpt showin reading and writing and would like to know if
I'm doing it right. (i.e: Is it bad code and what to improve).
Here are some improvements and my rationale (check my thinking):
- Initially, each method had its SQL statement(s) inside, but I grouped
all statements in a dictionary, with operations as keys, as a class
'constant' as per previous advice on this mailing list.
- Each method used sqlite3 module on its own, but it was repetitive so I
put that part in its own method `init_db` that returns a tuple
consisting in a connection and a cursor.
- Sometimes there was an exception raised, so I used `try` in `init_db`.
- Methods closed the connection themselves, so I used `with` in
`init_db` instead of `try`, as it would close the connection
automatically and rollback (I hope I'm not making this up).
Here's the excerpt (`DB_FILES` and `QUERIES` are not included here for
more clarity).
Thank you.
def __init__(self, phone):
# Get preliminary information on user and make them
# available.
self.phone = phone
self.known = self.find()
if self.known:
self.balance = self.get_balance()
else:
self.balance = None
def init_db(self):
with sqlite3.connect(self.DB_FILE) as conn:
return conn, conn.cursor()
def find(self):
'''Find the phone in the users database.'''
(__, cursor) = self.init_db()
try:
cursor.execute(
self.QUERIES['FIND_PHONE'],
(self.phone,)
)
found = cursor.fetchone()
return True if found else False
except Exception as e:
return self.ERROR.format(e.args[0])
def create(self, seed_balance):
''' Create a database entry for the sender.'''
conn, cursor = self.init_db()
try:
cursor.execute(
self.QUERIES['CREATE'],
(self.phone, seed_balance)
)
conn.commit()
except Exception as e:
return self.ERROR.format(e.args[0])
--
~Jugurtha Hadjar,
More information about the Tutor
mailing list