以连接postgresql为列
with 常用在python的文件操作上,替换了原始的open,close
with 语句实质是上下文管理。
1、上下文管理协议。包含方法__enter__() 和 __exit__(),支持该协议对象要实现这两个方法。
2、上下文管理器,定义执行with语句时要建立的运行时上下文,负责执行with语句块上下文中的进入与退出操作。
3、进入上下文的时候执行__enter__方法,如果设置as var语句,var变量接受__enter__()方法返回值。
4、如果运行时发生了异常,就退出上下文管理器。调用管理器__exit__方法。
所以在连接数据时只要有_enter__() 和 __exit__(),两个方法就可以实现对数据库的连接与断开
# -*- coding: utf-8 -*-
import json
import psycopg2
import psycopg2.extras
class DBclient():
def __init__(self):
db_link = {"database":"database","username":"username","password":"password","host":"host","port":"port"}
self.conn = psycopg2.connect(
database=db_link["database"],
user=db_link["username"],
password=db_link["password"],
host=db_link["host"],
port=db_link["port"])
self.cur = self.conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
def select(self, sql, params=None):
if params:
self.cur.execute(sql, params)
else:
self.cur.execute(sql)
result = self.cur.fetchall()
return json.dumps(result)
def insert(self, sql,params=None):
if params:
self.cur.execute(sql, params)
else:
self.cur.execute(sql)
def close(self):
self.cur.close()
self.conn.close()
def commit(self):
self.conn.commit()
class DBoperate(object):
def __init__(self):
self.db = DBclient()
def __enter__(self):
return self.db
def __exit__(self, exc_type, exc_val, exc_tb):
self.db.close()
return None
if __name__ == '__main__':
# sql_select = """
# select * from tb_name
# """
# params = [214]
# sql_select = """
# select * from tb_name where id = %s
# """
#
# sql_insert = """
# INSERT INTO tb_name ( id, name )
# VALUES( 1, '测试' )
# """
#
# params = {'id':1, 'name':'测试'}
# sql_insert = """
# INSERT INTO tb_name ( id, name )
# VALUES( %(id)s, %(name)s )
# """
# 实现对数据库的连接与断开
# with DBoperate() as db:
# query_set = db.select(sql_select, params=params)
# print(query_set)
#
# db.insert(sql_insert, params= params)
# db.commit()
pass