python学习笔记-数据库补充pymysql

一、pymysql

pymsql是Python中操作MySQL的模块,其使用方法和py2的MySQLdb几乎相同。

安装

pip install pymysql

用法

# import mysql.connector  #导入MySQL驱动
# db = mysql.connector.connect(host="127.0.0.1",
#                 port=3306,
#                 user="root",
#                 password="123456",
#                 database="test")
# check = db.cursor() #通过获取到的数据库连接db下的cursor()方法来创建游标。
# check.execute("SELECT * FROM tb_sp_hotwords;") #通过游标check操作execute()方法可以写入纯sql语句。通过execute()方法中写如sql语句来对数据进行操作。
# values = check.fetchall()
# print(values)
# check.close() #关闭游标
# db.close()

#使用pymysql模块
import pymysql #导入pymysql模块
db = pymysql.connect(host="127.0.0.1",
                port=3306,
                user="root",
                password="123456",
                database="test")
check = db.cursor() #通过获取到的数据库连接db下的cursor()方法来创建游标。
#check = db.cursor(corsor=pymysql.cursors.DictCursor)
#更改获取数据结果的数据类型,默认是元组,可以改为字典等:conn.cursor(cursor=pymysql.cursors.DictCursor)

check.execute("SELECT * FROM tb_sp_hotwords;") #通过游标check操作execute()方法可以写入纯sql语句。通过execute()方法中写入sql语句来对数据进行操作。
values = check.fetchall()
#check.scroll(1,mode="relative")   # 相对当前位置移动
#check.scroll(1,mode="absolute")   # 相对绝对位置移动

print(values)
check.close() #关闭游标
db.close()

 二、事务

事务指逻辑上的一组操作,组成这组操作的各个单元,要不全部成功,要不全部不成功。

数据库开启事务命令 

--        start transaction 开启事务
--        Rollback 回滚事务,即撤销指定的sql语句(只能回退insert delete update语句),回滚到上一次commit的位置
--        Commit 提交事务,提交未存储的事务
-- 
--        savepoint 保留点 ,事务处理中设置的临时占位符 你可以对它发布回退(与整个事务回退不同) 

例子:

create table test2(id int PRIMARY KEY auto_increment,name VARCHAR(20)) engine=innodb;
INSERT INTO test2(name) VALUE ("mark"),
                              ("jobs"),
                              (“haha");



start transaction;
insert into test2 (name)values('steve');
select * from test2;
commit;


-- 保留点

start transaction;
insert into test2 (name)values('max');
savepoint insert_max;
select * from test2;



delete from test2 where id=4;
savepoint delete1;
select * from test2;


delete from test2 where id=1;
savepoint delete2;
select * from test2;

rollback to delete1;


select * from test2;
View Code

python中调用数据库启动事务的方式

import pymysql

#添加数据

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='yyy')

cursor = conn.cursor()


try:
    insertSQL0="INSERT INTO ACCOUNT2 (name,balance) VALUES ('bob',4000)"
    insertSQL1="UPDATE account2 set balance=balance-30 WHERE name='mark'"
    insertSQL2="UPDATE account2 set balance=balance+30 WHERE name='haha'"

    cursor = conn.cursor()

    cursor.execute(insertSQL0)
    conn.commit()

    cursor.execute(insertSQL1)
    raise Exception
    cursor.execute(insertSQL2)
    cursor.close()
    conn.commit()

except Exception as e:

    conn.rollback()
    conn.commit()


cursor.close()
conn.close()
原文地址:https://www.cnblogs.com/steven223-z/p/13466053.html