数据库(四) sql注入问题

数据库

pymysql操作mysql

安装数据库

pip install pymysql

连接

==连接数据库的参数:==

conn = pymysql.connect(host='lpcalhost',user='rppt',password='123',database='test',chaarset='utf8',)
#coursor=conn.cursor()默认返回的值是元组类型
cursor = conn.cursor(cirsor=pymysql.cursors.DictCursor) #返回值是字典类型

pymysql的sql注入问题

用户可以不通过密码或者用户名就能登录

==产生的原因:==因为过于相信用户输入的内容,根本没有做任何效验。

==解决方法:==

通过格式化输出方式将用户名和密码做优化,客户必须输入才会进行效验。《sql = "select *from user where name=%s and password=%s" cursor.execute(sql,(user,pwd))》

pymysql增加数据

sql="inster into user(name,password) values(%s,%s)"
#cursor.execute(sql,('xxx','qwe'))##新增一条数据

data=[
    ('nick','123')
    ('tank','123')
    ('saon','123')
]
cursor.executemany(sql,data)##新增多条数据
###加如下代码块
conn.commit()
print(cursor.lastrowid) ##获取最后一行的id值

pymysql修改数据

sql='updata user set name=%s where id=%s'
cursor.execute(sql,('dgsahdsa',2))
conn.commit()
cursor.close()
conn.close()

pymysql查看数据

fetchall():取出所有的数据  返回的是列表套字典
fetchone():取出一条数据,返回的是字典
fetchmany(size):取出size条数据,返回的是列表套字典

pymysql删除数据

sql = 'delete from user where id=%s'
cursor.execute(sql,('dgsahddsa',2))
conn.commmit()
sursor.close()
conn.close()

索引

基础
  1. 索引的作用就是为了提高查询效率

  2. 索引的本质是一个特殊的文件

  3. 索引的原理 B+树

  4. 索引的种类:

    主键索引:加速查找+不能重复+不能为空 primary key

    唯一索引:加速查找+不能重复 unique(name)

    ​ 联合唯一索引:unique(name,email),例:akon 123@.com

    普通索引:加速查找 index(name)

    ​ 联合索引:index(name,email)

创建

==主键索引:==

新增主键索引:

create table xxx(id int auto_increment primary key)

alter table xxx change id id int auto_increment

primary key;

alter table t1 add primary key(id)

删除主键索引:

mysql>alter table t1 drop primary key;

==唯一索引:==

新增:

  1. create table t2(id int auto_increment primary key,name varchar(32) not null default ",unique u_name(name))charset utf8

  2. creat unique index 索引名 on 表名(字段名);

    create unique index is_name on t1(name);

  3. alter table t2 add unique index ix_name(name)

删除:

​ alter table t2 drop index u_name;

==普通索引:==

新增:

  1. create table t3(id int auto_increment primary key,

    name varchar(32) not null default",

    index u_name(name))charset utf8

  2. create index 索引名 on 表名(字段名);

    create index ix_name on t3(name);

  3. alter table t3 add index ix_name(name)

删除:

alter table t3 drop index u_name;

==索引的优缺点==

优点:提高查询效率

缺点:加索引后,会占用大量的磁盘空间

我把月亮戳到天上 天就是我的 我把脚踩入地里 地就是我的 我亲吻你 你就是我的
原文地址:https://www.cnblogs.com/zhulipeng-1998/p/12863925.html