pymysql模块及补充知识点

pymysql

  在python中通过模块pymysql操作数据库,首先通过pip3 install pymysql下载模块。

  接着我们编写连接数据库操作的基本代码:

复制代码
import pymysql

if __name__ == '__main__':
    # 创建数据库连接对象
    conn = pymysql.connect(
        host='127.0.0.1',  # ip地址
        port=3306,         # 端口号
        user='root',       # 用户名
        password='',       # 密码
        database='xzj',    # 数据库
        charset='utf8',    # 字符编码
        autocommit=True    # 是否自动提交事务
    )
    # 获得游标对象,指定游标类型DictCursor使查询结果返回为字典数据
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    # execute执行sql语句,返回值表示sql语句影响的行数
    affect_rows = cursor.execute('select * from student')
    # fetch**函数返回执行结果数据,默认不设置cursor类型返回元组
    print(cursor.fetchall())
    # 关闭连接
    conn.close()
复制代码

  常用函数

复制代码
# 执行单行
cursor.execute('select * from t')
# 批量执行
cursor.executemany(
    'insert into t(name,age) values(%s,%s)',
    (('xie',18),('lin',20))
)

# 调用以下fetch**函数会移动光标
cursor.fetchone()   # 查询一行,光标到底时返回none
cursor.fetchall()   # 查询所有,光标到底时默认返回()空元组
cursor.fetchmany(5) # 查询5行,光标到底时默认返回()空元组

# 移动光标,第一个参数是移动行数,第二个参数是模式
# relative:相对当前位置移动n行
# absolute:从顶行开始移动n行
cursor.scroll(0,'relative')
cursor.scroll(0,'absolute')
复制代码

 

  sql注入问题

  利用一些语法的特性 书写一些特点的语句实现固定的语法来跳过密码登录

  因此日常生活中很多软件在注册的时候都不能含有特殊符号,因为怕你构造出特定的语句入侵数据库,不安全。

  MySQL利用的是MySQL的注释语法。

"""
select * from user where name='jason' -- jhsadklsajdkla' and password=''

select * from user where name='xxx' or 1=1 -- sakjdkljakldjasl' and password=''
"""

 

  为解决这种问题就避免手动拼接字符串

复制代码
import pymysql


conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = '123456',
    database = 'day48',
    charset = 'utf8'  # 编码千万不要加-
)  # 链接数据库
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

username = input('>>>:')
password = input('>>>:')
sql = "select * from user where name=%s and password=%s"
# 不要手动拼接数据 先用%s占位 之后将需要拼接的数据直接交给execute方法即可
print(sql)
rows = cursor.execute(sql,(username,password))  # 自动识别sql里面的%s用后面元组里面的数据替换
if rows:
    print('登录成功')
    print(cursor.fetchall())
else:
    print('用户名密码错误')
复制代码

 

补充知识:事务

  事务的性质

    原子性(atomicity)
      一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
    一致性(consistency)
      事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
    隔离性(isolation)
      一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
    持久性(durability)
      持久性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响

  事务相关操作

    start transcation:开启事务

    sql操作

    rollback:回滚到操作之前的状态

    commit:确认事务操作 之后不能回滚

复制代码
# 先介绍事务的三个关键字 再去用表实际展示效果

create table user(
id int primary key auto_increment,
name char(32),
balance int
);

insert into user(name,balance)
values
('jason',1000),
('egon',1000),
('tank',1000);

# 修改数据之前先开启事务操作
start transaction;

# 修改操作
update user set balance=900 where name='jason'; #买支付100元
update user set balance=1010 where name='egon'; #中介拿走10元
update user set balance=1090 where name='tank'; #卖家拿到90元

# 回滚到上一个状态
rollback;

# 开启事务之后,只要没有执行commit操作,数据其实都没有真正刷新到硬盘
commit;
"""开启事务检测操作是否完整,不完整主动回滚到上一个状态,如果完整就应该执行commit操作"""

# 站在python代码的角度,应该实现的伪代码逻辑,
try:
    update user set balance=900 where name='jason'; #买支付100元
    update user set balance=1010 where name='egon'; #中介拿走10元
    update user set balance=1090 where name='tank'; #卖家拿到90元
except 异常:
    rollback;
else:
    commit;
复制代码

 

posted @   临江沂水  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示