# python前后文管理工具合同的完成

> 作者/来源: UCloud 运营管理员
> 发布时间: 2023-01-13T07:30:00.000Z
> 分类: 其他
> 标签: AI, 数据库, Python
> 原文链接: http://117.50.162.249:3000/yun/articles/625

---

# python前后文管理工具合同的完成

> 来源: https://www.ucloud.cn/yun/130274.html
> 作者: 89542767
> 发布日期: 发布于2023-01-13 15:30

本文关键阐述了python前后文管理工具合同的完成，在python中所有完成了前后文管理工具协议书目标都能用应用with实际操作，with开启了目标前后文管理工具

　　序言

　　在前后文管理工具协议书的过程当中，牵涉到2个魔术师方式\_\_enter\_\_方法与\_\_exit\_\_方式

　　在python中所有完成了前后文管理工具协议书目标都能用应用with实际操作

　　with开启了目标前后文管理工具

　　前后文管理工具协议书：

```
　　__enter__方式:进到enter方式返回最后被as后边的自变量接受
　　exit:撤出with中所有的句子执行完毕实行实行exit
　　完成简单的文件操作来看一下前后文管理工具协议书：
　　classMyOpen:
　　#创建对象
　　def__init__(self,filename,mode,encoding):
　　self.filename=filename
　　self.mode=mode
　　self.encoding=encoding
　　def__enter__(self):
　　print("---enter---方式")
　　#实行文件打开实际操作
　　self.f=open(self.filename,self.mode,encoding=self.encoding)
　　returnself.f
　　def__exit__(self,exc_type,exc_val,exc_tb):
　　"""
　　:paramexc_type:异常类型
　　:paramexc_val:异常信息
　　:paramexc_tb:出现异常追溯目标
　　:return:
　　"""
　　print('----enter---')
　　self.f.close()
　　withMyOpen('hr.txt','w',encoding='utf-8')asf:
　　print(f.write('现阶段开启了文档，载入了数据信息：23323232'))
```

　　用pymysql完成1个操作数据库的类，完成前后文管理工具协议书，完成撤出前后文时，自动退出游标卡尺，中断连接

　　todo:版本1

　　#todo:版本1：

```
　　classmysql_db(object):
　　#创建对象属性
　　def__init__(self):
```

　　1.连接数据库

```
　　self.cou=pymysql.connect(
　　host="数据库主机地址",
　　port=端口,
　　user="登录数据库的账号",
　　password="登录数据库的密码",
　　database="数据库名称",
　　charset='utf8',编码格式
　　cursorclass=pymysql.cursors.DictCursor  将默认的元组格式转换成字典格式输出
　　)
```

　　2.创建游标卡尺

```
　　self.cur=self.cou.cursor()
　　def__enter__(self):
　　returnself.cur   返回cur目标
　　def__exit__(self,exc_type,exc_val,exc_tb):
　　"""
　　:paramexc_type:异常类型
　　:paramexc_val:异常信息
　　:paramexc_tb:出现异常追溯目标
　　:return:
　　"""
　　#关闭游标卡尺
　　self.cur.close()
　　#关闭数据库连接
　　self.cou.close()
　　defObtain_one_date():
　　withmysql_db()asdb:
　　db.execute('select*fromt_customerLIMIT4')应用execute方法进行查询语句
　　content=db.fetchone()返回一条数据的查询的结果
　　print(content)
　　#函数调用
　　Obtain_one_date()
　　todo:版本2
　　sql='select*fromt_customerLIMIT4'
　　defmysql_db1(**kwargs):
　　returnpymysql.connect(host=kwargs.get('host','xxxx'),
　　user=kwargs.get("user",'xxxx'),
　　passwd=kwargs.get("passwd",'xxxx'),
　　database=kwargs.get("database",'xxxx'),
　　port=kwargs.get('port',xxxx),
　　charset=kwargs.get('charset','utf8'))
```

　　1.创建数据库连接目标

```
　　cou=mysql_db1()
```

　　2.创建游标卡尺

```
　　withcou.cursor()ascu:
　　cu.execute(sql)应用execute方法进行查询语句
　　commt=cu.fetchone()返回一条数据的查询的结果
　　print(commt)
　　#函数调用
　　mysql_db1()
```

       综上所述，这篇文章就给大家介绍到这里了，希望可以给大家带来帮助