zoukankan      html  css  js  c++  java
  • pymysql基本语法,sql注入攻击,python操作pymysql,数据库导入导出及恢复数据---day38

    1.pymysql基本语法

    # ### python操作mysql
    import pymysql
    '''
    # ### 1.基本语法
    #(1) 创建连接 host user password database 四个参数必写
    conn = pymysql.connect(host='127.0.0.1',user='root',password='',database='zuoye',charset='utf8',port=3306)
    #(2)创建游标对象,该对象可以进行增删改查操作
    cursor = conn.cursor()
    #(3)执行一个sql语句
    sql = 'select * from student'
    #返回的是数据的总条数
    res = cursor.execute(sql)
    print(res)
    #(4)获取数据
    res = cursor.fetchone()  #一条
    print(res)
    #(5)释放游标对象
    cursor.close()
    #(6)关闭连接
    conn.close()
    '''
    
    # ### 创建/删除  表
    '''
    conn = pymysql.connect(host='127.0.0.1',user='root',password='',database='db0620')
    cursor = conn.cursor()
    #1.创建一张表
    sql = """
    create table t1(
    id int unsigned primary key auto_increment,
    first_name char(10) not null,
    last_name char(10) not null,
    age int unsigned,
    sex tinyint,
    money float
    )
    """
    res = cursor.execute(sql)
    print(res)
    '''
    
    #2.查看表结构
    '''
    sql = "desc t1"
    res = cursor.execute(sql)
    print(res)  #6  返回字段个数
    print(cursor.fetchone())
    '''
    
    #3.删除表
    '''
    try:
        sql = "drop table t1"
        res = cursor.execute(sql)
        print(res)
    except:
        pass
    cursor.close()
    conn.close()
    '''
    
    # ### 3.事务处理
    '''
    begin;
    commit;
    rollback;
    python 操作事务处理 必须通过commit提交数据,才会真正的改变数据,否则进行rollback回滚恢复以前状态
    '''
    conn = pymysql.connect(host='127.0.0.1',user='root',password='',database='db0618')
    cursor = conn.cursor()
    sql1 = 'begin'
    # sql2 = 'select * from employee'
    sql3 = 'update employee set emp_name = "liuwei" where id = 1'
    sql4 = 'commit'  #必须要提交commit 不然数据不会改变
    sql5 = 'select * from employee'
    
    res1 = cursor.execute(sql1)
    # res2 = cursor.execute(sql2)
    res3 = cursor.execute(sql3)
    res4 = cursor.execute(sql4)
    res5 = cursor.execute(sql5)
    
    print(cursor.fetchone()) #获取下一行一条数据
    print(cursor.fetchone()) #会跟着上一条往下查询一条数据
    # print(res1,res2,res3,res4,res5)
    
    cursor.close()
    conn.close()

    2.sql注入攻击

    # ### sql注入攻击
    #创建一张表
    '''
    create table usr_pwd(
    id int unsigned primary key auto_increment,
    username varchar(255) not null,
    password varchar(255) not null
    )
    '''
    #(1) sql 注入问题
    import pymysql
    user = input("user:").strip()
    pwd = input("password:").strip()
    
    #创建连接对象
    conn = pymysql.connect(host='127.0.0.1',user='root',password='',database='db0619')
    #创建游标
    cursor = conn.cursor()
    
    sql = "select * from usr_pwd where username = '%s' and password = '%s'" % (user,pwd) #注意引号问题
    print(sql)
    
    res = cursor.execute(sql)
    print(res) #查询数据个数
    
    if res:
        print("登录成功")
    else:
        print("登录失败")
    cursor.close()
    conn.close()
    '''
    select * from usr_pwd where username = 'wdas3544' or 10 = 10 --324sdadf ' and password ='asdasd'
    where username = 'wdas3544' or 10=10 username的判断是假的,但是后面or拼接的条件是真的,所以可以查询成功
    --代表后面的代码是注释
    把用户名和密码都绕开了,进行sql注入攻击
    '''
    
    #(2) 解决办法
    '''
    使用预处理机制,可以避免绝大多数的sql注入问题
    execute(sql,(参数1,参数2,参数3...))
    execute 第一个参数是一个sql语句,如果sql语句和里面的参数值分开执行,默认开启预处理
    '''
    import pymysql
    user = input("user:").strip()
    pwd = input("password:").strip()
    
    conn = pymysql.conncet(host='127.0.0.1',user='root',password='',database='db0619')
    cursor = conn.cursor()
    sql = 'select * from usr_pwd where username = %s and password = %s'
    res = cursor.execute(sql,(user,pwd))
    
    if res:
        print("登录成功")
    else:
        print("登录失败")
    cursor.close()
    conn.close()

    3.python操作pymysql

    # ### python 操作mysql 增删改查
    import pymysql
    '''
    python操作mysql的时候默认开启事务,必须在增删改之后
    提交数据,才会对数据库产生影响,否则默认回滚
    提交数据:conn.commit()
    回滚数据:conn.rollback()
    
    execute 执行单条语句
    executemany 执行多条可加参数    
    '''
    #1.创建mysql连接
    conn = pymysql.connect(host='127.0.0.1',user='root',password='',database='db0619')
    #创建游标  #默认返回元组
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #设置返回字典
    sql = "select * from usr_pwd where username = 'liuwei' and password = '111'"
    res = cursor.execute(sql)
    print(res)
    print(cursor.fetchone()) #{'id': 1, 'username': 'liuwei', 'password': '111'}
    
    
    #
    """
    sql = "insert into t1(first_name,last_name,age,sex,money) values(%s,%s,%s,%s,%s)"
    #一次插入一条数据
    # res = cursor.execute(sql,("吴","号",23,1,12000))
    # print(res) #返回1,但是数据库没有数据,必须要手动commit提交
    
    #一次插入多条数据 列表嵌套元组的形式
    res = cursor.executemany(sql,[('jack','li',36,1,5000),('如','兰',25,0,6400),('天','天',26,1,9000)])
    print(res) #3 返回的是插入的条数
    
    #获取最后插入这条数据的id号
    '''
    插入单条,获取是最后的id号
    插入多条,获取的是以第一条为主的id,把多条当做一个整体
    '''
    print(cursor.lastrowid) #16 插入了三条 获取的是三条里面第一条的id号
    
    #针对多条数据最后的id,可以通过倒序查询,找到id号
    # select id from t1 order by id desc limit 1;
    """
    
    #
    """
    sql = 'delete from t1 where id =%s'
    res = cursor.execute(sql,(18))
    print(res) #成功就是1,失败就是0
    if res:
        print("删除成功")
    else:
        print("删除失败")
    """
    
    #
    """
    sql = 'update t1 set first_name = %s where id = %s'
    res = cursor.execute(sql,('小',11))
    print(res) #成功返回1,失败返回0
    if res:
        print("更新成功")
    else:
        print("更新失败")
    """
    
    #
    sql = 'select * from t1'
    res = cursor.execute(sql)
    print(res) #总条数
    #(1)获取一条数据 fetchone
    res = cursor.fetchone()
    print(res)
    
    #(2)获取多条数据 fetchmany  返回列表嵌套字典,不写参数默认获取一条,并从之前获取的那一条往下获取
    data = cursor.fetchmany()
    data = cursor.fetchmany(3) #获取3条数据从上一条数据往下获取
    print(data)
    '''
    [{'id': 4, 'first_name': '王', 'last_name': '八', 'age': 45, 'sex': 0, 'money': 3400.0}, 
    {'id': 5, 'first_name': '七', 'last_name': '七', 'age': 23, 'sex': 1, 'money': 4550.0}, 
    {'id': 6, 'first_name': '小', 'last_name': '白', 'age': 54, 'sex': 1, 'money': 12000.0}]
    '''
    for row in data:
        first_name = row["first_name"]
        last_name = row["last_name"]
        age = row["age"]
        if row["sex"] == 0:
            sex = "女性"
        else:
            sex = "男性"
        money = row["money"]
        print(f"姓:{first_name},名:{last_name},年龄:{age},性别:{sex},收入:{money}")
    
    #(3)获取所有数据 fetchall 返回列表嵌套字典,基于上一条数据往下搜索
    # data = cursor.fetchall()
    # print(data)
    
    #(4)自定义搜索查询的位置
    sql = 'select * from t1 where id>=3'
    res = cursor.execute(sql)
    print(res) #返回满足查询的所有条数
    res = cursor.fetchone()
    print(res)
    
    
    #1.相对滚动 向后滚 不能超过数据范围
    cursor.scroll(3,mode='relative')#滚动3条数据
    res = cursor.fetchone() #查的话是查滚动3条数据后所在位置的下一条数据
    print(res)
    #向前滚 不能超过数据范围
    cursor.scroll(-2,mode='relative') #向前滚动2条数据
    res = cursor.fetchone()#查的话是查向前滚动2条数据后所在位置的下一条数据
    print(res)
    
    #2.绝对滚动,永远基于第一条数据的位置进行滚动
    cursor.scroll(0,mode='absolute') #0就是第一个位置
    print(cursor.fetchone())
    cursor.scroll(3,mode='absolute') #基于第一条数据的位置滚动3条
    print(cursor.fetchone())#查的话是查滚动3条数据后所在位置的下一条数据
    #往前滚没数据,因为是永远基于第一条数据的位置进行滚动 error 超出范围
    cursor.scroll(-1,mode='absolute')
    print(cursor.fetchone())
    
    #在进行增删改的时候,必须通过commit提交数据,才会对数据库进行更新,否则默认回滚
    conn.commit() #提交数据
    cursor.close()
    conn.close()

    4.数据库导入导出及恢复数据

    # 导出数据库  -d是表结构  不加-d 是表结构和表数据
    #第一步:先退出数据库 q退出数据库
    #第二步:切换到对应的导出路径 如d盘 d:
    #第三步:执行命令
            #导出整个数据库:
            mysqldump -uroot -p密码  数据库名 > 数据库名.sql
            #导出某个数据库下的一个表
            mysqldump -uroot -p密码  数据库名 表名 > 表名.sql
            #导出某个数据库下多个表
            mysqldump -uroot -p密码  数据库名 表名 表名 表名 > 表名.sql
    
    #导入数据库
    #第一步:先创建一个空的数据库
    #第二步:找到对应的sql文件的路径
    #第三步:source 路径/sql文件
    
    
    
    
    #只有frm和ibd如何恢复数据库
    #innodb 在只有frm和ibd文件的情况下,如何恢复数据
    #安装MySQL Utilities
    '''
    cmd中找到frm那个文件,执行如下命令:
    切换到对应目录,执行下面语句,不要加分号
    mysqlfrm --diagnostic ./文件目录/t1.frm
    查出建表语句,赋值查询出来的建表语句在mysql中创建的新数据中使用
    
    对已创建的表进行表空间卸载,删除ibd文件
    mysql> alter table t1 discard tablespace;
    
    把要恢复的ibd文件替换进去
    
    对已创建的表进行空间装载
    mysql> alter table employee import tablespace;
    '''
    
    '''
    当数据库爆炸了和不能启动了可以这样操作
    myisam存储的数据:
    先在mysql数据库的安装位置data目录下新建一个数据库文件夹,然后把之前数据库中的
    三个文件(myisam2.frm,myisam2.MYD,myisam2.MYI)塞到这个新建的数据库文件夹中,就可以恢复数据了
    '''
    
    '''
    innodb存档的数据:
    安装MySQL Utilities,
    然后在mysql数据库安装位置下的data下新建一个数据库文件夹,然后把之前你要恢复的数据库中的frm文件扔到
    这个新建的文件夹中,然后打开cmd,找到现在这个存放frm文件的新的数据库文件夹路径,
    然后执行命令mysqlfrm --diagnostic ./frm文件,(执行命令会解析建表语句),然后复制建表语句,然后把现在新的数据库文件夹
    下的frm文件删除掉,然后在cmd中登录mysql,去用复制的建表语句去创建表,
    执行完建表语句后,需要先卸载空间,执行alter table 表名 discard tablespace;
    然后再把之前表里面的ibd文件扔到新的数据库文件夹下,然后在cmd中执行命令装载alter table 表名 import tablespace;
    
    '''
  • 相关阅读:
    Nodejs中的流
    Openstack Havana的两个排错过程
    Mongoose入门
    Promise
    CSS3中的动画
    MySql学习笔记(一)--安装配置
    应用Dubbo框架打造仿猫眼项目(二) 影片模块开发
    应用Dubbo框架打造仿猫眼项目(一) 用户模块开发
    4种事务的隔离级别
    JAVA面试题解惑系列(一)——类的初始化顺序
  • 原文地址:https://www.cnblogs.com/weiweivip666/p/13174594.html
Copyright © 2011-2022 走看看