pip install pymysqlmysql
==链接数据库的参数:==sql
conn = pymysql.connect(host='lpcalhost',user='rppt',password='123',database='test',chaarset='utf8',) #coursor=conn.cursor()默认返回的值是元组类型 cursor = conn.cursor(cirsor=pymysql.cursors.DictCursor) #返回值是字典类型
用户能够不经过密码或者用户名就能登陆数据库
==产生的缘由:==由于过于相信用户输入的内容,根本没有作任何效验。fetch
==解决方法:==优化
经过格式化输出方式将用户名和密码作优化,客户必须输入才会进行效验。《sql = "select *from user where name=%s and password=%s" cursor.execute(sql,(user,pwd))》code
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值
sql='updata user set name=%s where id=%s' cursor.execute(sql,('dgsahdsa',2)) conn.commit() cursor.close() conn.close()
fetchall():取出全部的数据 返回的是列表套字典 fetchone():取出一条数据,返回的是字典 fetchmany(size):取出size条数据,返回的是列表套字典
sql = 'delete from user where id=%s' cursor.execute(sql,('dgsahddsa',2)) conn.commmit() sursor.close() conn.close()
索引的做用就是为了提升查询效率索引
索引的本质是一个特殊的文件ip
索引的原理 B+树ci
索引的种类:
主键索引:加速查找+不能重复+不能为空 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;
==惟一索引:==
新增:
create table t2(id int auto_increment primary key,name varchar(32) not null default ",unique u_name(name))charset utf8
creat unique index 索引名 on 表名(字段名);
create unique index is_name on t1(name);
alter table t2 add unique index ix_name(name)
删除:
alter table t2 drop index u_name;
==普通索引:==
新增:
create table t3(id int auto_increment primary key,
name varchar(32) not null default",
index u_name(name))charset utf8
create index 索引名 on 表名(字段名);
create index ix_name on t3(name);
alter table t3 add index ix_name(name)
删除:
alter table t3 drop index u_name;
==索引的优缺点==
优势:提升查询效率
缺点:加索引后,会占用大量的磁盘空间