python访问数据库是日常编程中经常使用的,一般的代码如下:

可以看出样例代码还是比较多的,有没有办法优化一下呢?有!

def send_msgs(conn_id=None, **kwargs):
    conn = get_mysql_conn(conn_id)
    cursor = conn.cursor()
    sql_db = '''select count(1) from table)'''
    cursor.execute(sql_db)
    result = cursor.fetchone()
    cursor.close()
    conn.close()

 

采用python提过的上下文方式,访问数据库就可以这样写:

def send_msgs(conn_id=None, **kwargs):
    with db_conn(conn) as cur:
        cur.execute(sql)
        r1=cur.fetchone()

 

缩减了一半以上的代码,而且还可以自动关闭,db_conn怎么写?就是实现下面这样一个类就可以了:

class db_conn(object):

    def __init__(self, conn_id):
        self.conn = MySqlHook.get_connection(conn_id=conn_id).get_hook().get_conn()
        self.cur = self.conn.cursor()

    def __enter__(self):
        return self.cur

    def __exit__(self, exc_type, exc_value, exc_trace):
        self.conn.commit()
        self.cur.close()
        self.conn.close()

 

相关文章:

  • 2021-10-08
  • 2022-01-06
  • 2021-07-07
  • 2021-07-11
  • 2021-12-18
  • 2021-10-07
猜你喜欢
  • 2021-12-16
  • 2021-11-15
  • 2022-12-23
  • 2021-07-13
  • 2021-04-10
  • 2021-08-19
  • 2021-09-12
相关资源
相似解决方案