寻找一种更Python化的方式来访问数据库

编程入门 行业动态 更新时间:2024-10-24 21:37:18
本文介绍了寻找一种更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) 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化的方式来访问数据库

本文发布于:2023-10-27 23:35:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534861.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   数据库   来访问   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!