我有一堆遵循这种模式的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) connmit() 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:
jessenoller/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 ...
- docs.python/2.5/whatsnew/pep -343.html
- docs.python/2.5/whatsnew/pep-343.html
更多推荐
寻找一种更Python化的方式来访问数据库
发布评论