我是靠谱客的博主 激动银耳汤,这篇文章主要介绍python 操作 mysql (简单好用的封装)本文需要使用 pymysql 包,现在分享给大家,希望可以做个参考。

@[TOC](python 操作 mysql (简单好用的封装))

本文需要使用 pymysql 包

导包(使用代理网址,速度快些)

复制代码
1
2
3
pip install -i https://pypi.douban.com/simple PyMySQL

工具类的封装

复制代码
1
2
工具简单的封装查询和修改方法,revise 主要执行对数据库的增删改查
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import pymysql class SqlUtil(object): def __init__(self,host,port,username,password,db): self.db = pymysql.connect(host=host, port=port, user=username, passwd=password,db=db, charset='utf8') def query(self, sql): cursor = self.db.cursor() cursor.execute(sql) return cursor.fetchall() def revise(self, sql): try: cursor = self.db.cursor() cursor.execute(sql) # 执行SQL语句 self.db.commit() # 提交到数据库执行 return True except: self.db.rollback() # 发生错误时回滚 return False def close(self): self.db.close()

使用

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import SqlUtil # 导入你的工具类文件,如在别的目录,使用from .. import SqlUtil host='localhost' port = 3306 username = 'root' password = 'root' db='db1' su=SqlUtil(host,port,username,password,db) sql='select * from t' result = su.query(sql) print(result) sql1 = 'delete from t where id = 1' result1=su.revise(sql1) print(result1) su.close()

最后

以上就是激动银耳汤最近收集整理的关于python 操作 mysql (简单好用的封装)本文需要使用 pymysql 包的全部内容,更多相关python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(78)

评论列表共有 0 条评论

立即
投稿
返回
顶部