操作流程
- 创建连接
- 获取游标
- 执行sql
a. 查询操作(select)
b. 非查询操作(insert/update/delete)
ⅰ. 事务提交(连接对象.commit())
ⅱ. 事务回滚(连接对象.rollback()) - 关闭游标
- 关闭连接
`import pymysql
创建连接
conn = pymysql.connect(
host="localhost",
port=3306,
user="root",
password="0000",
database="db01"
)
cursor = conn.cursor()
执行mysql
cursor.execute("select version()")
result = cursor.fetchall()
print(result)
关闭游标
cursor.close()
关闭连接
conn.close()
PyMySQL增删改查
import pymysql
创建连接
conn = pymysql.connect(
host="localhost",
port=3306,
user="root",
password="0000",
database="db01",
autocommit=True
)
cursor = conn.cursor()
执行mysql
查找
sqls = "select * from tab01;"
cursor.execute(sqls)
print("获取查询结果记录的行数:", cursor.rowcount)
print("获取第一条数据", cursor.fetchone())
print("获取全部结果", cursor.fetchall())
更新游标
cursor.rownumber = 0
print("获取所有数据:", cursor.fetchall())
增加
sqls = "insert into tab01 values (7449,'book',900,'CLERK',20)"
cursor.execute(sqls)
修改
sqls = "update tab01 set name='cook' where name='book'"
cursor.execute(sqls)
print(cursor.rowcount)
删除
sqls = "delete from tab01 where name='cook'"
cursor.execute(sqls)
print(cursor.rowcount)
关闭游标
cursor.close()
关闭连接
conn.close()
增加事务操作后:
import pymysql
创建连接
conn = pymysql.connect(
host="localhost",
port=3306,
user="root",
password="0000",
database="db01"
)
cursor = conn.cursor()
try:
sqls = "insert into tab01 values (7449,'book',900,'CLERK',20)"
cursor.execute(sqls)
print(cursor.rowcount)
print("-" * 20)
主动抛出异常
raise Exception("程序出错")
print("-" * 20)
sqls = "insert into tab02 values (7400,'cook','CLERK',7900,1990-11-11,800,200,10)"
cursor.execute(sqls)
print(cursor.rowcount)
print("-" * 20)
提交事务
conn.commit()
except Exception as e:
回滚
conn.rollback()
print(e)
finally:
关闭游标
if cursor:
cursor.close()
关闭连接
if conn:
conn.close()`
MySQL事务
并发控制的基本单位。事务是一个操作序列,这些操作要么都执行要么都不执行,不可分割。
事务特征
- 原子性:事务中包含的操作被看作一个逻辑单元
- 一致性:事务的结果保留不变,即事务的运行并不改变数据的一致性
- 隔离性:事务的中间状态对其他事务是不可见的
- 持久性:指一个事务一旦提交成功,对数据库中数据的改变就应该是永久性的
autocommit=True # 自动事务提交
PyMySQL的封装
``import pymysql
class DBUtil():
初始化
__conn = None
__cursor = None
创建连接
@classmethod
def __get_conn(cls):
if cls.__conn is None:
cls.__conn = pymysql.connect(
host="localhost",
port=3306,
user="root",
password="0000",
database="db01"
)
return cls.__conn
获取游标
@classmethod
def __get_cursor(cls):
if cls.__cursor is None:
cls.__cursor = cls.__get_conn().cursor()
return cls.__cursor
执行mysql
@classmethod
def exe_sql(cls, sql):
try:
获取游标 调用execute方法,执行mysql
cursor = cls.__get_cursor()
cursor.execute(sql)
如果查询返回所有数据
if sql.split()[0].lower() == "select":
return cursor.fetchall()
如果不是查询语句
else:
# 提交事务
cls.__conn.commit()
返回受影响行数
return cursor.rowcount
except Exception as e:
出现异常,进行事务回滚
cls.__conn.rollback()
print(e)
finally:
关闭游标
cls.__close_cursor()
关闭连接
cls.__close_conn()
关闭游标
@classmethod
def __close_cursor(cls):
if cls.__cursor:
cls.__cursor.close()
cls.__cursor = None
关闭连接
@classmethod
def __close_conn(cls):
if cls.__conn:
cls.__conn.close()
cls.__conn = None
`调用改封装
from mysqldb import DBUtil
sql = "select * from tab01"
result = DBUtil.exe_sql(sql)
print(result)
sql = "insert into tab01 values(1000,'book',4000,'CLERK',20)"
result = DBUtil.exe_sql(sql)
print(result)
sql = "update tab01 set id=100 where id=1000"
result = DBUtil.exe_sql(sql)
print(result)
sql = "delete from tab01 where id=100"
result = DBUtil.exe_sql(sql)
print(result)``