Python pymysql操作MySQL详细
发布日期:2021-12-31 18:15 | 文章来源:CSDN
1、使用
1.1 简单使用
import pymysql
# 创建连接
con = pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='test',charset='utf8'
)
# 创建游标
cursor = con.cursor()
# 执行新增SQL,返回受影响行数
row1 = cursor.execute("insert into user (username, password) values ('username3','password3')")
print(row1)
# 执行更新SQL,返回受影响行数
row2 = cursor.execute("update user set password = '123456' where id > 2;")
# 执行查询SQL
res = cursor.execute("SELECT * FROM user;")
result = cursor.fetchall()
for info in result:
print(info[0], info[1])
# 提交,不然无法保存新增或者更新的数据
con.commit()
# 关闭游标
cursor.close()
# 关闭连接
con.close()
注意:数据库表中存在中文时,创建连接需要指定charset='utf8',否则中文显示会乱码。 其中cursor.fetchall()是获取所有结果集,如果只有一条结果集,可以使用cursor.fetchone() 。
1.2 封装工具类
为了使用方便,可以直接封装成工具类:
import pymysql class MysqlHelper: def __init__(self, config): self.host = config["host"] self.port = config["port"] self.user = config["user"] self.password = config["password"] self.db = config["db"] self.charset = config["charset"] self.con = None self.cursor = None def create_con(self): """ 创建连接 """ try: self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.db, charset='utf8') self.cursor = self.con.cursor() return True except Exception as e: print(e) return False # def close_con(self): """ 关闭链接 """ if self.cursor: self.cursor.close() if self.con: self.con.close() # sql执行 def execute_sql(self, sql): """ 执行插入/更新/删除语句 """ try: self.create_con() print(sql) self.cursor.execute(sql) self.con.commit() except Exception as e: print(e) finally: self.close_con() def select(self, sql, *args): """ 执行查询语句 """ try: self.create_con() print(sql) self.cursor.execute(sql, args) res = self.cursor.fetchall() return res except Exception as e: print(e) return False finally: self.close_con()
使用工具类:
config = {
"host": 'localhost',
"port": 3306,
"user": 'root',
"password": '123456',
"db": 'test',
"charset": 'utf8'
}
db = MysqlHelper(config)
db.execute_sql("insert into user (username, password) values ('username4','password4')")
db.select("SELECT * FROM user;")
到此这篇关于Python pymysql操作MySQL详细的文章就介绍到这了,更多相关Python pymysql操作MySQL内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。
相关文章
关注官方微信