执行下面指令安装pymysql
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ pymysql
本次演示需要的表的结构如下:
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(64) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`sex` VARCHAR(1) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`age` INT(10) NULL DEFAULT NULL,
`username` VARCHAR(64) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`password` VARCHAR(256) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`remark` VARCHAR(64) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`create_at` DATETIME(6) NULL DEFAULT NULL,
`update_at` DATETIME(6) NULL DEFAULT NULL,
`email` VARCHAR(64) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `username` (`username`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1
;
import pymysql
import datetime
# 第一步:获取连接
connection = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", db="test", charset='utf8')
# 第二步:获取cursor对象
cursor = connection.cursor()
# 第三步:编写sql
date1 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') # 2023-08-11 11:03:56.788851
sql = f"insert into user(name,username,password,sex,age,create_at,update_at) values('zhangsan1','98981','marry1','1','18','{date1}','{date1}')"
# 第四步:开启事务
connection.begin()
# 第五步:执行sql
count = cursor.execute(sql)
print("count:", count)
# 第六步:提交事务
connection.commit()
import pymysql
# 第一步:获取连接
connection = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", db="test", charset='utf8')
# 第二步:创建cursor
cursor = connection.cursor()
# 第三步:编写sql
sql = "select * from user"
# 第四步:执行SQL
cursor.execute(sql)
# 第五步:查看结果集 (fetchall,查询所有数据)
emps = cursor.fetchall()
# 第六步:便利输出数据
for e in emps:
print(e, end="\n")
import pymysql
# 第一步:获取连接
connection = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", db="test", charset='utf8')
# 第二步:获取cursor对象
cursor = connection.cursor()
# 第三步:编写sql
sql = "update user set age=19 where id=1"
# 第四步:开启事务
connection.begin()
# 第五步:执行sql
count = cursor.execute(sql)
print("count:", count)
# 第六步:提交事务
connection.commit()
import pymysql
# 第一步:获取连接
connection = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", db="test", charset='utf8')
# 第二步:获取cursor对象
cursor = connection.cursor()
# 第三步:编写sql
sql = "delete from user where id=1"
# 第四步:开启事务
connection.begin()
# 第五步:执行sql
count = cursor.execute(sql)
print("count:", count)
# 第六步:提交事务
connection.commit()
上面通过四个简单的例子做了增删改查的操作,采用上面的方式进行参数的赋值的话存在sql注入的风险,下面的例子优化sql的入参。
import pymysql
import datetime
# 第一步:获取连接
connection = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", db="test", charset='utf8')
# 第二步:获取cursor对象
cursor = connection.cursor()
# 第三步:编写sql(通过占位符占位,避免sql注入的风险)
date1 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') # 2023-08-11 11:03:56.788851
sql = "insert into user(name,username,password,sex,age,create_at,update_at) values(%s,%s,%s,%s,%s,%s,%s)"
# 第四步:开启事务
connection.begin()
# 第五步:执行sql(传入具体的参数)
count = cursor.execute(sql, ('zhangsan2', '98981', 'marry1', '1', '18', date1, date1))
print("count:", count)
# 第六步:提交事务
connection.commit()
在实际的业务执行过程中,往往还是涉及到执行过程中出现异常,需要将已执行的sql进行回滚,可以通过下面的例子实现
from datetime import datetime
import pymysql
connection = None
cursor = None
try:
# 第一步:获取连接
connection = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", db="test",
charset='utf8')
# 第二步:获取cursor对象
cursor = connection.cursor()
# 第三步:编写sql(通过占位符占位,避免sql注入的风险)
date1 = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') # 2023-08-11 11:03:56.788851
sql = "insert into user(name,username,password,sex,age,create_at,update_at) values(%s,%s,%s,%s,%s,%s,%s)"
# 第四步:开启事务
connection.begin()
# 第五步:执行sql(传入具体的参数)
count = cursor.execute(sql, ('zhangsan2', '98981', 'marry1', '1', '18', date1, date1))
print("count:", count)
# 第六步:提交事务
connection.commit()
except Exception as e:
print(e)
# 出现错误回滚事务
if connection:
connection.rollback()
finally:
# 最后关掉连接
if cursor:
cursor.close()
if connection:
cursor.close()
import pymysql
class DBUtil:
config = {
"host": "127.0.0.1",
"user": "root",
"password": "root",
"db": "test",
"charset": "utf8"
}
def __init__(self):
self.connection = pymysql.connect(**DBUtil.config)
self.cursor = self.connection.cursor()
def close(self):
if self.cursor:
self.cursor.close()
if self.connection:
self.connection.close()
# 插入 修改 删除调用
def exeDML(self, sql, *args):
try:
# 执行sql
count = self.cursor.execute(sql, args)
# 提交事务
self.connection.commit()
return count
except Exception as e:
print(e)
if self.connection:
self.connection.rollback()
finally:
self.close()
def query_one(self, sql, *args):
try:
# 执行sql
self.cursor.execute(sql, args)
# 获取结果集
return self.cursor.fetchone()
except Exception as e:
print(e)
finally:
self.close()
def query_all(self, sql, *args):
try:
# 执行sql
self.cursor.execute(sql, args)
# 获取结果集
return self.cursor.fetchall()
except Exception as e:
print(e)
finally:
self.close()