【Python】操作MySQL

安装第三方库:

复制代码
pip install pymysql

由于MySQL经常需要使用到增删改查,为此,提供一个工具类

python 复制代码
# 数据库操作类

import pymysql

DB_CONFIG = {
	"host": "127.0.0.1",
	"port": 3306,
	"user": "root",
	"passwd": "123456",
	"db": "test",
	"charset": "utf8"
}

class SQLManager(object):

	# 初始化实例方法
	def __init__(self):
		self.conn = None
		self.cursor = None
		self.connect()

	# 连接数据库
	def connect(self):
		self.conn = pymysql.connect(
			host=DB_CONFIG["host"],
			port=DB_CONFIG["port"],
			user=DB_CONFIG["user"],
			passwd=DB_CONFIG["passwd"],
			db=DB_CONFIG["db"],
			charset=DB_CONFIG["charset"]
		)
		self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

	# 查询多条数据
	def get_list(self, sql, args=None):
		self.cursor.execute(sql, args)
		return self.cursor.fetchall()

	# 查询单条数据
	def get_one(self, sql, args=None):
		self.cursor.execute(sql, args)
		return self.cursor.fetchone()

	# 执行单条SQL语句
	def modify(self, sql, args=None):
		row = self.cursor.execute(sql, args)
		self.conn.commit()
		return row > 0

	# 执行多条SQL语句
	def multi_modify(self, sql, args=None):
		rows = self.cursor.executemany(sql, args)
		self.conn.commit()
		return rows > 0

	# 关闭数据库cursor和连接
	def close(self):
		self.cursor.close()
		self.conn.close()
相关推荐
databook10 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar11 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户83562907805111 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_11 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
得物技术15 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
Java水解15 小时前
【MySQL】从零开始学习MySQL:基础与安装指南
后端·mysql
数据智能老司机18 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机19 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机19 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机19 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构