Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looking for a more pythonic way to access the database

Tags:

python

mysql

I have a bunch of python methods that follow this pattern:

def delete_session(guid):
    conn = get_conn()
    cur = conn.cursor()

    cur.execute("delete from sessions where guid=%s", guid)

    conn.commit()
    conn.close()

Is there a more pythonic way to execute raw sql. The 2 lines at the beginning and end of every method are starting to bother me.

I'm not looking for an orm, I want to stick with raw sql.

like image 905
Ben Noland Avatar asked Dec 09 '22 20:12

Ben Noland


1 Answers

You could write a context manager and use the with statement. For example, see this blog post:

http://jessenoller.com/2009/02/03/get-with-the-program-as-contextmanager-completely-different/

Also the python documentation has a sample that pretty much matches your needs. See section 8.1 on this page, in particular the snippet that begins:

db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...
  • https://docs.python.org/2.5/whatsnew/pep-343.html
like image 199
ars Avatar answered Dec 13 '22 14:12

ars