寻找一种更Python化的方式来访问数据库 [英] looking for a more pythonic way to access the database

查看:67
本文介绍了寻找一种更Python化的方式来访问数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()

是否存在更多的Python方式来执行原始sql.每种方法开头和结尾的两行都开始困扰我.

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.

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

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

推荐答案

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

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/

此外,python文档中的示例非常符合您的需求.请参阅此页面上的8.1节,尤其是开头的代码段:

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
    • https://docs.python.org/2.5/whatsnew/pep-343.html
    • 这篇关于寻找一种更Python化的方式来访问数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆