01_最基本的数据库连接


# pip install pymysql

import pymysql

try:
# 1. 创建链接
# class Connection: 类 类的入口是 def __init__(
# 忘记可以 鼠标光标移到 connect 上,按住 control ,点进去
conn = pymysql.connect(
user="root", # 用户名
# (1045, "Access denied for user 'root'@'localhost' (using password: YES)") 这个报错就是密码错了
password="1234", # 密码
host="localhost", # 自己的机器就写 localhost
database="spider", # 链接mysql里面的哪一个
port=3306, # 端口号
)

# 运行,没有报错,就是链接成功

# 2. 创建游标 目标:执行sql语句
cursor = conn.cursor()

# 3. 准备sql stu_new 表名
sql = "insert into stu_new(sname, sage, score, sgender, class) values " \
"('娃哈哈', 18, 66, 1, '七年五班')"

# 4. 执行sql
result = cursor.execute(sql)
print(result) # 返回 1 表示执行成功,插入一条,执行一条
# print(1/0)
# 5. 提交事务 pymysql 存东西的时候,执行没有问题,数据库就是没有东西,就是没有提交,必须手动提交
conn.commit()
# 数据库刷新没有添加成功
# pymysql在执行sql的时候,默认开启了事务
# 1 2 3 4 5 6 7 8 9 10 假设是一页数据
# 假设到5的时候出现问题,有俩中解决办法,1. 开启事务的话,出问题自动清除前面4条数据,也叫回滚,保证一页数据的完整 2. 没有开启事务,前面4条数据保存到数据库,后面出错就不要了


except:
conn.rollback()

finally: # 最终
if cursor:
cursor.close()
if conn:
conn.close() # 一定记得关闭连接


# 关于事务俩个操作: rollback 回滚 commit 提交
posted @ 2023-08-11 22:54  严永富  阅读(5)  评论(0)    收藏  举报