sudo apt-get install mysql-server mysql-client
根据提示,设置root用户的密码
sudo service mysql start #开启 sudo service mysql stop #关闭 sudo service mysql restart #重启
sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
将bind-address=127.0.0.1注释
sudo service mysql restart
mysql -uroot -p
然后输入root账户密码
grant all privileges on *.* to 'root'@'%' identified by '安装时设置的密码' with grant option; flush privileges;
exit
mysql -uroot -p
然后输入root账号密码
grant all privileges on 数据库名.表名 to '用户名'@'主机名' identified by '密码' with grant option; flush privileges;
grant all privileges on test_database.* to 'test'@'%' identified by '123' with grant option; flush privileges;
use mysql;
update user set authentication_string = password('新密码') where user = '用户名' and host = '主机名';
password()为mysql自身的一个加密函数
update user set authentication_string = password('456') where user = 'test' and host = '%';
revoke all on 数据库名.表名 from '用户名'@'主机名'; flush privileges;
drop user '用户名'@'主机名';
create database 数据库名 charset=utf8;
drop database 数据库名;
use 数据库名;
show databases;
select database();
sudo -s
cd /var/lib/mysql
mysqldump -uroot -p 需要备份的数据库名 > /path/备份文件名.sql #后面重定向的路径自定义
mysql -uroot -p
create database 恢复后数据库名 charset=utf8;
exit
mysql -uroot –p 恢复后数据库名 < /path/备份文件.sql
show tables;
create table 表名 (字段1 类型 约束,字段2 类型 约束...);
CREATE TABLE `user_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `age` tinyint(4) NOT NULL, `phone_num` char(11) NOT NULL, `gender` bit(1) DEFAULT b'1', PRIMARY KEY (`id`), UNIQUE KEY `phone_num` (`phone_num`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
alter table 表名 add 字段名 类型;
alter table 表名 change 原字段名 新字段名 新字段类型;
alter table 表名 modify 字段名 新类型;
alter table 表名 drop 字段名;
desc 表名;
show create table 表名;
rename table 原表名 to 新表名;
drop table 表名;
select * from 表名;
select distinct gender as '性别' from user_info;
select distinct id,gender from user_info; #由于id不可能相同,所以不会消除重复
select distinct name from user_info order by gender desc; #错误写法 select distinct name,gender from user_info order by gender desc; #正确写法
select * from 表名 where 条件;
select * from students where isdelete=0; #查询没被删除的学生 select * from students where id>3; #查询编号大于3的学生 select * from subjects where id<=4; #查询编号不大于4的科目 select * from students where sname!='黄蓉'; #查询姓名不是“黄蓉”的学生
select * from students where gender=0 and id>3; #查询编号大于3的女同学 select * from students where isdelete=0 or id<4; #查询编号小于4或没被删除的学生
select * from students where sname like '黄%'; #查询姓黄的学生 select * from students where sname like '黄_'; #查询姓黄并且名字是一个字的学生 select * from students where sname like '黄%' or sname like '%靖%'; #查询姓黄或者名字中含有靖的学生
select * from students where id in(1,3,8); #查询编号是1,3,8的学生 select * from students where id between 3 and 8; #查询编号是3-8的学生
select * from students where hometown is null; #查询没有填写地址的学生 select * from students where hometown is not null and gender=0; #查询填写了地址的女生
聚合能够快速得到统计数据,以下提供了5个聚合函数:
select count(*) from students; #查找学生总数 select max(age) from students where gender=0; #查询女生最大年龄 select min(id) from students where isdelete=0; #查询未删除的学生最小编号 select sum(id) from students where gender=1; #查询男生的编号之和 select avg(age) from students where gender=1; #查询男生的平均年龄
select 列1,列2,聚合... from 表名 group by 字段1,字段2,字段3...
select gender as 性别, count(*) as 人数 from students group by gender; #查询男女生人数
select 列1,...聚合... from 表名 group by 字段1,...having 条件;
having后面的条件运算符与where的相同,但是选择集不同,where是对from后面指定的表进行数据筛选,属于对原始数据的筛选,having是对group by的结果进行筛选
select gender as 性别, count(*) as 总数 from students group by gender having gender=1; #查询男生人数
select * from 表名 order by 字段1 asc|desc,字段2 asc|desc,...
select * from students where gender=1 order by id desc; 按学号降序查询男生信息
select * from 表名 limit start,count;
从start开始,获取count条数据,start索引从0开始,如果不写start,则默认start=0,表示从第1个数据开始,获取count条
select * from 表名 where... limit (n-1)*m, m;
如果第n页数据不足m条,则显示当前页的实际条数
select distinct * from 表名 where .... group by ... having ... order by ... limit star,count;
实际使用中,只是语句中某些部分的组合,而不是全部
insert into 表名 values(0,...);
主键列是自增的,但是在全列插入时需要占位,通常使用0,插入成功后自动会添上正确的数值
insert into 表名 values(0,...),(0,...)...;
insert into 表名(字段1,...) values(值1,...);
insert into 表名(字段1,...) values(值1,...),(值1,...)...;
update 表名 set 字段1=值1,... where 条件...;
delete from 表名 where 条件;
# 通常会增加一个字段isdelete,默认为0 alter table 表名 add isdelete bit default 0; # 如果需要删除则修改isdelete=1 update 表名 set isdelete=1 where ...;
create table scores( id int primary key auto_increment, stuid int, subid int, score decimal(5,2), foreign key(stuid) references students(id), foreign key(subid) references subjects(id) );
alter table 表名 add constraint 约束名 foreign key(字段名) references 主表名(id); #其中约束名可以任意起 alter table scores add constraint stu_sco foreign key(stuid) references students(id);
show create table 表名;
alter table 表名 drop foreign key 约束名;
alter table 表名 add constraint 约束名 foreign key(字段名) references 主表名(id) on delete 级联操作类型; alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade;#主表数据删掉,从表中相关联记录都将删除
当查询的结果来源于有关系的多张表时,需要使用到连接查询
查询学生的姓名、总分
select students.sname 姓名,sum(scores.score) 总分 from scores inner join students on scores.stuid=students.id group by students.sname;
select students.sname 姓名,subjects.stitle 科目,scores.score 成绩 from scores inner join students on scores.stuid=students.id inner join subjects on scores.subid=subjects.id;
select province.atitle 省名,city.atitle 市名 from areas as province inner join areas as city on province.id = city.pid where province.atitle = '山西';
select atitle 市名 from areas where pid = (select id from areas where atitle = '山西省');
select * from students where id in (select max(id) from students group by gender);
select @rownum:=@rownum+1 rownum,name,age from (select name,age from students where gender=1) stu,(select @rownum:=0) row;
注:@变量名:=value是给变量赋值,from后面两个临时表用','隔开,表示全相乘
select name from category as cat where exists(select 1 from goods where goods.cat_id = cat.id );
select name as 姓名,(select score from scores inner join subjects on scores.sub_id = subjects.id where subjects.title = '数学' and stu_id = stu.id) as '数学' from students stu;
create view 视图名 as select ...
通常视图名以v_开头便于区分
show tables;
同查看表的操作相同
alter view 视图名 as select ...;
select * from 视图名;
show create table 表名;
alter table 表名 engine=innodb;
begin; insert into students(name,age,gender) values('张三',25,1); update students set age=28 where name='李四'; delete from students where name='王五'; commit; #或者rollback;
create index 索引名 on 表名(字段名1,...);
如果只有一个字段名,表示建立单列索引;多个字段名,表示建立组合索引。如果字段为字符类型,可以在字符后面指定长度,比如students(name(20),age),也可以不指定,其他类型(int,bit)的字段不需要指定长度
show index from 表名;
drop index 索引名 on 表名;
set profiling = 1; #开启监测工具 select * from areas where atitle = '北京市'; #执行查询语句 show profiles; #查看查询执行时间 create index title_index on areas(atitle); #为atitle字段创建索引 select * from areas where atitle = '北京市'; #再次执行查询语句 show profiles; #再次查看执行时间
pip3 install PyMySQL
import pymysql
conn = pymysql.connect(host="主机",port=3306,user="用户名",passwd="密码",db="数据库名",charset="utf8")
如果是本机,host填'localhost',port端口号,默认3306,charset字符编码,默认是'gb2312',要求与数据库创建时指定的编码一致,否则中文会乱码
cur = conn.cursor()
# coding = utf-8 import pymysql con = pymysql.connect(host='localhost',port=3306,user='root',password='123',db='test',charset='utf8') # 创建connect对象 cur = conn.cursor() #创建cursor对象 name = input('请输入添加的学生姓名:') sql1 = 'insert into students(name) values(%s);' sql2 = 'delete from students where name = "老王";' sql3 = 'update students set name = “老张” where name = "老李";' try: cur.execute(sql1,[name]) #增加一条数据 cur.execute(sql2) #删除一条数据 cur.execute(sql3) #修改一条数据 except Exception as e: print(e) con.rollback() # 放弃之前的所有操作 else: con.commit() # 提交,使所有操作生效 cur.close() # 关闭cursor对象
# coding = utf-8 import pymysql con = pymysql.connect(host='localhost',port=3306,user='root',password='123',db='test',charset='utf8') # 创建connect对象 cur = conn.cursor() #创建cursor对象 try: sql = 'select * from students;' count = cur.execute(sql) data1 = cur.fetchone() #查找第一行数据 print(data1) data2 = cur.fetchall() # 查找剩下所有行数据 print(data2) except Exception as e: print(e) cur.close() con.close()