Ai
2 Star 0 Fork 1

jackfrued/python2004

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
example04.py 1.00 KB
一键复制 编辑 原始数据 按行查看 历史
jackfrued 提交于 2020-11-27 15:20 +08:00 . 添加functools模块的例子
"""
查询操作
"""
import MySQLdb
# 1. 创建连接对象
from MySQLdb.cursors import DictCursor
from utils import connect
class Dept:
def __init__(self, no, name, location):
self.no = no
self.name = name
self.location = location
def __str__(self):
return f'{self.no}\t{self.name}\t{self.location}'
if __name__ == '__main__':
conn = connect(database='hrs')
try:
# 2. 获取游标对象
with conn.cursor(cursorclass=DictCursor) as cursor:
# 3. 通过游标对象向数据库发出SQL语句获取执行结果
cursor.execute('select dno as no, dname as name, dloc as location from tb_dept')
# 4. 通过游标抓取数据
# - fetchone / - fetchmany / - fetchall
for row in cursor.fetchall():
dept = Dept(**row)
print(dept)
except MySQLdb.MySQLError as err:
print(err)
finally:
# 5. 关闭数据库连接(释放资源)
conn.close()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/jackfrued/python2004.git
git@gitee.com:jackfrued/python2004.git
jackfrued
python2004
python2004
master

搜索帮助