Python 操作 mysql

目录

Python 操作 mysql

  • 基本语法

  • 创建/删除 表

  • 事务处理

sql注入攻击

  • sql 注入的现象

  • 使用预处理,提前对sql语句中的特殊符号进行处理

python 操作 MySQL 增删改查

恢复数据

 

 

 

Python 操作 mysql

  • 基本语法

  • # (1) 创建连接  host  user  password  database 这四个参数必须写
    conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db0826",charset="utf8",port=3306)
    # (2) 创建游标对象(该对象可以操作数据库增删改查)
    cursor = conn.cursor()
    print(cursor)
    # (3) 执行sql语句
    sql = "select * from employee"
    # 返回的是数据的总条数
    res = cursor.execute(sql)
    print(res)
    # (4)获取数据 fetchone 获取一条
    res = cursor.fetchone()
    res = cursor.fetchone()
    print(res)
    # (5) 释放游标对象
    cursor.close()
    # (6) 关闭连接
    conn.close()

     

  • 创建/删除 表

  • conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db0826")
    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())
    print(cursor.fetchone())
    print(cursor.fetchone())
    print(cursor.fetchone())
    print(cursor.fetchone())
    print(cursor.fetchone())
    """
    
    # (3).删除表
    """
    try:
        sql = "drop table t1"
        res = cursor.execute(sql)
        print(res)
    except:
        pass
    """
    cursor.close()
    conn.close()

     

  • 事务处理

  • """
    pymysql 操作事务处理时,需要commit提交数据,才会变化,否则rollback回滚.恢复到最初状态
    """
    conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db0826")
    cursor = conn.cursor()
    sql1 = "begin"
    sql2 = "update employee set emp_name = '123egon' where id = 1"
    sql3 = "commit"
    res1 = cursor.execute(sql1)
    res2 = cursor.execute(sql2)
    res3 = cursor.execute(sql3)
    # print(res1,res2,res3) # 返回值没有意义
    # fetchone 与查询sql有关 , 增删改无效;
    # tup = cursor.fetchone()
    # print(tup)
    
    cursor.close()
    conn.close()

     

sql注入攻击

  • sql 注入的现象

  • # (1) sql注入的现象
    import pymysql
    user = input("请输入用户名: >>> ").strip()
    pwd = input("请输入密码: >>> ").strip()
    conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db0826")
    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()
    
    输入时 : sfsdf' or 3=3 -- sdfsd
    # -- 后面的字符串都会被注释掉, 前面账号虽然是错的 但是 2=2是真的 绕开了账号和密码的判断;
    select * from usr_pwd where username='afasdfasdfasdf' or 2=2 -- sfasdf' and password='3434

     

  • 使用预处理,提前对sql语句中的特殊符号进行处理

  • """
    使用预处理机制,可以避免绝大多数sql注入的问题
    execute 如果参数为2个,将默认开启预处理
    execute(sql , (参数1,参数2,参数3 .... ) )
    """
    import pymysql
    user = input("请输入用户名: >>> ").strip()
    pwd = input("请输入密码: >>> ").strip()
    
    conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db0826")
    cursor = conn.cursor()
    sql = "select * from usr_pwd where username=%s and password=%s"
    res = cursor.execute(sql, (user,pwd) )
    
    print("登陆成功" if res  else "登录失败")
    
    cursor.close()
    conn.close()

     

python 操作 MySQL 增删改查

"""
    python 操作mysql时,默认开启事务,必须在增删改之后
    提交数据,才会真正对数据库发生变化,默认默认是回滚
    
    提交数据: conn.commit()
    回滚数据: conn.rollback()
    
    execute      一次插入一条
    executemany  一次插入多条
"""
import pymysql
# 1.创建mysql 链接
conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db0826")
# 查询数据,默认是元组,可以设置返回的类型为字典 pymysql.cursors.DictCursor
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor=pymysql.cursors.DictCursor
################ (1) 增
"""
sql = "insert into t1(first_name,last_name,age,sex,money) values(%s,%s,%s,%s,%s)"

# 一次插入一条
res = cursor.execute(sql, ("宋","云杰",30,0,15000) )
print(res) # 1
# 获取最后插入这条数据的id号(针对单条数据插入)
print(cursor.lastrowid) # 3

res = cursor.executemany(  sql,  [  ("高","云峰",50,1,16000) , ("戈","隆",80,1,17000) , ("袁","伟倬",120,0,130000) , ("刘","欣慰",150,0,18000)   ]   )
print(res) # 插入的条数
# 针对于多条数据,搜最后的id 可以通过倒序查询id
sql = "select id from t1 order by id desc limit 1"
res = cursor.execute(sql)
print(res)
# 获取最后一个id号
res = cursor.fetchone()
print(res)
"""

################### 删
"""
sql = "delete from t1 where id = %s"
res = cursor.execute(sql , (3,))
print(res)
if res:    
    print("删除成功")
else:
    print("删除失败")
"""

################## 改
"""
sql = "update t1 set first_name = %s where id = %s"
res = cursor.execute(sql,("王",4))
print(res)

if res:
    print("修改成功")
else:
    print("修改失败")
"""

#################### 查
"""
fetchone  fetchmany fetchall 都是基于上一条数据往下查询.
"""
sql = "select * from t1"
res = cursor.execute(sql)
print(res) # 总条数

# (1) 获取一条数据 fetchone
# {'id': 4, 'first_name': '王', 'last_name': '云杰', 'age': 30, 'sex': 0, 'money': 15000.0}
res = cursor.fetchone()
print(res)

# (2) 获取多条数据 fetchmany
data = cursor.fetchmany() # 默认搜索的的是一条数据
print(data)
data = cursor.fetchmany(3)
print(data) 

"""
[
{'id': 6, 'first_name': '高', 'last_name': '云峰', 'age': 50, 'sex': 1, 'money': 16000.0}, 
{'id': 7, 'first_name': '戈', 'last_name': '隆', 'age': 80, 'sex': 1, 'money': 17000.0}, 
{'id': 8, 'first_name': '袁', 'last_name': '伟倬', 'age': 120, 'sex': 0, 'money': 130000.0}
]
"""

for row in data :
    # print(row)
    first_name = row["first_name"]
    last_name = row["last_name"]
    age = row["age"]
    if row["sex"] == 0:
        sex = "女性"
    else:
        sex = "男性"
    
    money = row["money"]
    print("姓:{},名:{},年龄:{},姓名:{},收入:{}".format(first_name,last_name,age,sex,money)  )

# (3) 获取所有数据 fetchall
"""
data = cursor.fetchall()
print(data)
"""
# (4) 自定义搜索查询的位置

sql = "select * from t1 where id >= 20"
res = cursor.execute(sql)
print(res)
"""
# 1.相对滚动 (正数相对于当前位置往后滚,负数反之.)
cursor.scroll(3,mode="relative")
res = cursor.fetchone()
print(res)

cursor.scroll(3,mode="relative")
res = cursor.fetchone()
print(res)

# 27 往前滚
cursor.scroll(-2,mode="relative")
res = cursor.fetchone()
print(res)
"""

# 2.绝对滚动 , 永远基于第一条数据的位置进行移动
cursor.scroll(0,mode="absolute")
print(cursor.fetchone())

cursor.scroll(1,mode="absolute")
print(cursor.fetchone())

cursor.scroll(3,mode="absolute")
print(cursor.fetchone())

# 往前滚没有数据,超出范围error
"""
cursor.scroll(-1,mode="absolute")
print(cursor.fetchone())
"""

# 在进行增删改查时,必须提交数据,才会产生影响.
conn.commit()
cursor.close()
conn.close()

 

恢复数据

# innodb 在只有frm和ibd文件的情况下,如何恢复数据;

安装 MySQL Utilities
https://downloads.mysql.com/archives/utilities/ 

cmd中找到frm那个文件,执行如下命令:
切换到对应目录,执行下面语句,不要加分号
mysqlfrm --diagnostic ./文件目录/t1.frm
查出建表语句,复制查询出来的建表语句在mysql中创建的新数据中使用


#对已创建的表进行表空间卸载 删除ibd文件
mysql> alter table t1 discard tablespace;


把要恢复的idb文件替换进去


#对已创建的表进行空间装载
mysql> alter table t1 import tablespace;


CREATE TABLE `t1` (
  `id` int(11) DEFAULT NULL,
  `name` char(9) DEFAULT NULL
) ENGINE=InnoDB;

 

posted @ 2020-10-15 22:08  liuun  阅读(154)  评论(0)    收藏  举报