User Management -sql injection attacks - ** pymysql Application Index **

1. User Management

主要为了控制权限,让不同开发者,仅能操作属于自己的业务范围内的数据 

Creating an account myqsl

Three data related to accounts

账户名 密码  ip地址  

ip是用于限制某个账户只能在那些机器上登录 
create user 用户名@主机地址  identified by "密码";

# 注意:操作用户 只能由root账户来进行


# 删除 将同时删除所有权限
drop user 用户名@主机地址;

authority management

Related to the table

user   与用户相关信息
db      用户的数据库权限信息
tables_priv   用户的表权限
columns_priv  用户的字段权限 

grammar:

grant all  on *.*  to 用户名@主机地址  identified by "密码";

# 如果用户不存在则自动创建新用户,推荐使用
grant all  on *.*  to rose@localhost  identified by "123";


grant all  on day42.*  to rose1@localhost  identified by "123";


grant all  on day42.table1  to rose2@localhost  identified by "123";


grant select(name),update(name)  on day42.table1  to rose3@localhost  identified by "123";



all表示的是对所有字段的增删改查  
*.*  所有库的所有表 


收回权限 
revoke all on *.* from 用户名@主机地址;


revoke all on day42.table1 from rose2@localhost;


# 刷新权限
flush privileges;



#with grant option   表示 可以将他拥有的权限授予其它的用户
grant all  on *.*  to root1@localhost  identified by "123" with grant option;



# 授予某个用户 可以在任何主机上登录
grant all  on *.*  to jack10@"%"  identified by "123";
grant all  on *.*  to jack10@localhost  identified by "123";

练习:在你的mysql 为你的同桌创建一个账号

2. Visualization Client

mysqlworkbench

3.pymysql

pymysql  是一个第三方模块,帮我们封装了,建立连接,用户认证,sql'的执行以及,结果的获取

Basic use

import pymysql

"""
1.连接服务器
2.用户认证
3.发送指令
4.提取结果 
"""
# 1. 连接服务器  获取连接对象(本质上就是封装号的socket)
conn = pymysql.connect(
    host = "127.0.0.1",  #如果是本机 可以忽略
    port = 3306,    # 如果没改过 可以忽略
    user = "root", #必填
    password = "111", #必填
    database = "day42" #必填
)

# 2.通过连接拿到游标对象
# 默认的游标返回的是元组类型 不方便使用,需要更换字典类型的游标
c = conn.cursor(pymysql.cursors.DictCursor)

# 3.执行sql
sql = "select  * from table1"
res = c.execute(sql)
# 查询语句将返回查询的结果数量
# 4.提取结果
# print(res)
# print(c.fetchall())
# 5.关闭连接
c.close()
conn.close()

# 移动光标 参数1位移动的位置   mode 指定 相对或绝对
# c.scroll(1,mode="absolute")

# print(c.fetchall())

# print(c.fetchmany(1))
print(c.fetchone())
print(c.fetchone())

sql injection attacks

Means that some programmers, when the input data according to the syntax specification sql, data submitted for attack purposes

How to avoid this problem

Do validation on the server side sql sql before execution

Verify operation pymysql and packaging, we only need to do the stitching parameters can be handed over to pymysql

change the data

Case:

import pymysql
conn = pymysql.connect(
    host = "127.0.0.1",  #如果是本机 可以忽略
    port = 3306,    # 如果没改过 可以忽略
    user = "root", #必填
    password = "111", #必填
    database = "day42", #必填,
    #autocommit=False  # 开启自动提交  不常用....
)
c = conn.cursor(pymysql.cursors.DictCursor)
name = input("name:")
pwd = input("pwd:")
sql = "select *from user where name = %s"
if c.execute(sql,(name,)):
    print("用户名已存在!")
else:
    sql2 = "insert  into user values(%s,%s)"
    if c.execute(sql2,(name,pwd)):
        print("注册成功!")
        conn.commit() # 调用连接对象的提交函数
    else:
        print("注册失败!")
c.close()
conn.close()

Note: pymysql automatically open transaction, so submitting ourselves in the right position

Call a stored procedure

# 创建名为add1的存储过程
delimiter |
create procedure add1(in a int,in b int,out c int)
begin
set c = a + b;
end|
delimiter ;


#pymysql中调用
import pymysql
conn = pymysql.connect(
    host = "127.0.0.1",  #如果是本机 可以忽略
    port = 3306,    # 如果没改过 可以忽略
    user = "root", #必填
    password = "111", #必填
    database = "day42", #必填,
    autocommit=True  # 开启自动提交  不常用....
)
c = conn.cursor(pymysql.cursors.DictCursor)
c.callproc("add1",(1,2,1212)) # @_add1_0  @_add1_1  @_add1_2
c.execute("select @_add1_2")
print(c.fetchone())

# 调用存储过程时,传入参数,会自动定义成变量,
# 命名方式 @_过程的名称_参数的索引 从0开始

Application affairs

import pymysql
conn =pymysql.connect(
    user='root',
    password ='root',
    database ='day'
)

c=conn.cursor(pymysql.cursors.DictCursor)
try:#捕捉异常
    c.execute('start transaction;')
    sql1="update sa set salary =salary-1000 where name='张二狗'"
    c.execute(sql1)
    sql2 ="update sa set salary=salary+1000 where name ='李四狗'"
    c.execute(sql2)
    c.execute('commit;')
except:
    c.execute('rollback')
c.close()
conn.close()

4. Index

1.定义:
一种特殊的数据结构, 它存储的是数据的关键信息 与详细的信息 位置对应关系
类似于用书本的目录查书更快

2.为什么用索引:
加速查询,当数据量非常大的时候,查询某一个数据是非常慢的,索引用处在此

3.索引的影响:
>不是说有了索引就能加速,得看查询语句有没有正确的使用索引
>索引是需要占用额外的数据空间的  (光有书本  +目录的话 目录会有些许纸张)
>添加索引后,将导致增删修改变慢 也就是写入

4.何时添加索引,何时需要用到索引:
¥查询操作较多的 数据量很大的 并且写入过程很少
% 查询与写入占比为10:1 或者查询占比更多
* 本质上的索引其实就是减少搜索范围

磁盘 IO

The average search takes at least a data 9ms

This time cpu will switch to another program

To speed up query, you must reduce the number of small operations io

Index data structure

------ b + tree (tree structure to the image)

Leaf nodes store the actual data is, the more leaves, the higher the level of the tree, resulting in more number of operations io

---- avoid problems as much as possible to store more data in a leaf node, it should be a small amount of data as the index field

Leftmost matching principle

When the data item is a compound b + tree data structure, such as (name, age, sex) when (multi-column joint index), b + tree search tree will be established in accordance with the order from the left, such as when (Zhang, 20, F) so that the time to retrieve the data, b + tree name priority comparison determines the next search direction, if the same name and age Sex comparison in turn, finally obtained data retrieved; but (20, F) such data is not to name the time, b + tree node does not know what the next step to the investigation, because the time to establish the search tree name is the first comparative factor, you must first name according to the search query in order to know where to go next . For example, when (Zhang, F) ​​to retrieve such data, b + tree name can be used to specify the search direction, but the lack of age next field, so only the name is equal to the seating of the data is found, then the matching sex F of the data, this is a very important property, namely the left-most matching characteristics of the index.

### 聚集索引

​   聚集索引中包含了所有字段的值,如果拟定了主键,,主键就是聚集索引

如果没有  那就找一个非空且唯一的字段最为聚集索引

再找不着,自动生成一个字段最为聚集索引

### 辅助索引

​   除了聚集索引以外的都叫做辅助索引

辅助索引中只包含当前的索引字段和主键的值

### 覆盖查询

​   指的是当前索引结构中就能找到的所需要的数据,

如果使用的是聚集索引来查询那么一定是覆盖查询,速度是最快的

### 回表查询

​   指的是当前索引结构中找不到所需的数据,需要通过id去聚集索引中查询,速度慢与聚集索引

to sum up:

1. Use the smallest footprint possible as an index field

2. Do not store too much data in a row, for example, said the video, too many fields, then you can score sheet

3. Use queries as cover

4. If the field is case of low (high repetition), indexing does not make sense, in turn, should be to distinguish between high as the index field

5. fuzzy matching, try not EDITORIAL percent sign

6. Do not have calculated where age / 2 = 9 X -----> where age = 18 (a mode) On the lefthand side

7.and statement will automatically find the field with a compact edition of the first, it should contain at least we have an index in a field and statement

8. OR 语句要避免使用,如果要用则保证所有字段都有索引才能加速
9. 联合索引中,顺序应该将区分度最高的放在左边,最低的放在右边

Query must ensure that the leftmost index appear in the statement

Also note: If the amount of data to be queried very large index can not be accelerated

Conclusion: Instead of adding the index will be able to speed up, added to the need to consider whether a reasonable index, sql statement is to use index

Guess you like

Origin www.cnblogs.com/zhuyuanying123--/p/11209209.html