def get_conn():
host="myhost"
user="myuser"
password="mypass"
db="mydb"
conn = MySQLdb.connect(host=host, user=user, passwd=password, db=db)
return conn
def get_user(user_id):
conn = get_conn()
cur = conn.cursor()
cur.execute("select id, user_name from users where id = %s", user_id)
result = cur.fetchone()
user_info = User(id=result[0], user_name=result[1])
conn.commit()
conn.close()
return user_info
Refactorings
No refactoring yet !
ielectric.myopenid.com
July 9, 2009, July 09, 2009 08:04, permalink
You should take a look at sqlalchemy, you can use plain dbapi with all the neat features it provides.
Doug
August 5, 2009, August 05, 2009 10:40, permalink
I'd strongly recommend using SQLAlchemy (http://www.sqlalchemy.org/).
If you're creating a web app then using a full framework like TurboGears or Django would be your best route to take.
William Bowers
October 6, 2009, October 06, 2009 07:38, permalink
You can also use Django's ORM (http://docs.djangoproject.com/en/dev/topics/db/) without actually having to use Django. That's Django's design philosophy (or one of them?) -- keep everything separate. Anyway, having used both Django's ORM and SQLAlchemy, I would highly recommend going the Django route, or at least trying both so you can make your own decision.
Seun Osewa
October 29, 2009, October 29, 2009 05:57, permalink
Use the 'with' statement:
def get_conn():
host="myhost"
user="myuser"
password="mypass"
db="mydb"
conn = MySQLdb.connect(host=host, user=user, passwd=password, db=db)
return conn
def get_user(user_id):
with get_conn() as cur:
cur.execute("select id, user_name from users where id = %s", user_id)
result = cur.fetchone()
user_info = User(id=result[0], user_name=result[1])
return user_info
I have some database access code with a bunch of functions that follow a similar pattern to the get_user() function I've attached. I haven't spent much time working in python or with MySQLdb so any pythonic tips are appreciated.
You'll notice that I have 2 boiler plate lines at the beginning and end of every function. It would be nice to cut down on those.
Also it would be nice if I could index into the result by column name rather than numerical index (result["user_name"] rather than result[1]).