python使用上下文管理器操作数据库
2018-03-10 10:55
274 查看
with 语法用于简化资源操作的后续清除操作,是 try/finally 的替代方法,实现原理建立在上下文管理器之上
代码如下,数据库相关操作依库from pymysql import *
class DB():
def __init__(self, my_database1, my_password):
self.conn = connect(host='localhost', port=3306, database=str(my_database1), user='root', password=str(my_password),
charset='utf8')
self.cs1 = self.conn.cursor()
def __enter__(self):
return (self.cs1, self.conn)
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
self.cs1.close()
with DB('jing_dong','mysql') as (db, dbcoon):
count = db.execute('''select * from goods;''')
content = db.fetchall()
print(content)
for i in range(len(content)):
print(content[i])
i += 1
db.execute('''insert into goods(name,price) values('鞋子','200');''')
dbcoon.commit()
代码如下,数据库相关操作依库from pymysql import *
class DB():
def __init__(self, my_database1, my_password):
self.conn = connect(host='localhost', port=3306, database=str(my_database1), user='root', password=str(my_password),
charset='utf8')
self.cs1 = self.conn.cursor()
def __enter__(self):
return (self.cs1, self.conn)
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
self.cs1.close()
with DB('jing_dong','mysql') as (db, dbcoon):
count = db.execute('''select * from goods;''')
content = db.fetchall()
print(content)
for i in range(len(content)):
print(content[i])
i += 1
db.execute('''insert into goods(name,price) values('鞋子','200');''')
dbcoon.commit()
相关文章推荐
- 使用 python 操作 access 数据库
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- Python:操作PostgreSQL数据库(使用PyGreSQL)
- (转)[Python]MySQLdb for Python使用指南/Python的数据库操作【http://www.cnblogs.com/czh-liyu/archive/2008/04/13/1151758.html】
- 【转】MySQLdb for Python使用指南/Python的数据库操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- python数据库操作常用功能使用详解(创建表/插入数据/获取数据)
- Python学习之使用Python操作Redis数据库
- MySQLdb for Python使用指南/Python的数据库操作
- Python使用MySQLdb for Python操作数据库教程
- Python使用MySQLdb for Python操作数据库教程
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- Python使用PyGreSQL操作PostgreSQL数据库教程
- 使用Python操作MSSQL数据库.
- Python:操作PostgreSQL数据库(使用DB API2.0)
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- MySQLdb for Python使用指南/Python的数据库操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- 使用Python 2.7 CURD 操作非关系型数据库MongoDB