寻找更加pythonic的方式来访问数据库

Ben*_*and 4 python mysql

我有一堆遵循这种模式的python方法:

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

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

    conn.commit()
    conn.close()
Run Code Online (Sandbox Code Playgroud)

是否有更pythonic方式来执行原始SQL.每种方法开始和结束时的2行开始困扰我.

我不是在寻找一个orm,我想坚持使用原始sql.

ars*_*ars 8

您可以编写上下文管理器并使用with语句.例如,请参阅此博客文章:

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

此外,python文档还有一个非常符合您需求的示例.请参阅本页8.1节,特别是开头的代码段:

db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...
Run Code Online (Sandbox Code Playgroud)