【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()
相关推荐
聚名网10 分钟前
域名net,com,cn有区别吗?有哪些不同呢?
服务器·开发语言·php
牛油果子哥q13 分钟前
STL set与map底层精讲,红黑树适配原理、有序去重特性、迭代器遍历、API实战与面试核心考点全解
开发语言·数据结构·c++·面试
foundbug99915 分钟前
直流电机 PID 速度控制 MATLAB 仿真程序
开发语言·matlab
yoothey1 小时前
MySQL事务机制解析 - 面试高分知识点
数据库·mysql·面试
Tian_Hang1 小时前
C++原型模式(Protype)
开发语言·c++·算法
天天讯通2 小时前
OKCC 呼叫中心安全性能全解析:技术防护与管理措施指南
大数据·开发语言·网络·人工智能·安全·语音识别
JOJO数据科学2 小时前
JupyterLab Electron 鸿蒙 PC 适配全记录:从 Python 原生崩溃到 node-static 本地工作台
python·electron·harmonyos
xufengzhu2 小时前
第三方 Python 库 redis-py + hiredis 的使用
开发语言·redis·python
jingling5552 小时前
go | 环境安装和快速入门
开发语言·后端·golang
yuan199972 小时前
欧拉梁静力与屈曲计算的 MATLAB 实现(有限差分法 + 解析解)
开发语言·算法·matlab