python_mysql

python + mysql —-> pymysql

'''
数据库连接处理
1. 通过程序操作数据库会自动开启事务
2, 如果数据表不支持事务则执行语句后立即生效
3. 如果数据表支持事务,则需要提交才能修改,否则默认结束为回滚
'''
import pymysql

# 连接数据库  连接本机库可以不写host port
db = pymysql.connect(
    host="localhost",
    port=3306,
    user='root',
    password='200371',
    database='stu',
    charset='utf8'
)

# 生成一个游标:调用sql语句得到执行结果集的对象
cur = db.cursor()

# 数据库写操作  增删改
# 执行sql语句  class -> InnoDB  hobby -> MyISAM
try:
    sql = 'update class set score=100 where id=2;'
    cur.execute(sql)
    sql = 'delete from class where socre<60;'
    cur.execute(sql)
    db.commit() # 事务提交
except Exception as e:
    print(e)
    db.rollback() # 事务回滚

# 关闭游标和数据库连接
cur.close()
db.close()
github