1.数据库简介
1.1数据库简介
1.1.1概念
- 按照一定的数据结构来存储和管理数据的仓库
- 计算机是如何处理数据的?(主要放在磁盘和内存中)
1.1.2分类
- 关系型数据库(SQL):存储方式固定,安全
- 非关系型数据库(NoSQL (Not Only SQL)):存储方式比较灵活,存储数据的效率比较高, 不太安全
1.2区别
2.MySQL基本结构
2.1MySQL简介
2.1.1概念
- 最流行的关系型数据库管理系统之一
- 性能高、成本低、可靠性好、最流行的开源数据库之一
2.1.2特点
- 关系型数据库管理系统:采用关系模型来组织管理数据的数据库系统
- 把数据保存在不同的表中,而不是将数据放在一个大仓库中
- 可以运行于多个系统上,并且支持多种编程语言,包括C、C++、Python、Java、Perl、PHP、Ruby等
2.2MySQL组织数据的基本格式
2.3MySQL表中的数据
2.4总结
3.MySQL库级和表级操作
3.1MySQL进入与退出
3.1.1进入
-
mysql –uusername -ppassword
mysql -uroot -pqwe123;
mysql -uroot -p; 再输入密码qwe123(此处密码不会显示出来)
3.1.2退出
exit;
3.1.3创建数据库用户
- 如果出现:ERROR 1396 (HY000): Operation CREATE USER failed for ‘lirui’@’%’,则先:drop user ‘lirui’@’%’;
- 开始创建:create user ‘lirui’@’%’ identified by ‘abc123’;
3.1.4查看所有用户
select user,host from mysql.user;
3.2库级操作语句
3.2.1显示所有的库
show databases;
3.2.2创建库
-
create database [if not exists] db_name;
create database if not exists StudentDb; 重复创建会报错, 可以加上if not exists
3.2.3删除库
-
drop database [if exists] db_name;
drop database if exists StudentDb; 如果不知道数据库是否存在,记得加if exists
3.2.4进入数据库
-
use db_name;
use StudentDb;
3.2.5查看当前数据库
select database();
3.3表级操作语句
3.3.1显示所有的表
- show tables;
3.3.2创建表
-
create table [if not exists] tb_name(create definition…);
create table if not exists course(id int,name varchar(20)); 重复创建会报错, 可以加上if not exists
3.3.3显示创建表的信息
-
show create table tb_name;
show create table course;
-
describe(desc) tb_name;
describe(desc) course;显示格式比较美观
3.3.4删除表
-
drop table [if exists] tb_name;
drop table if exists course; 如果不知道表是否存在,记得加if exists
3.4注意事项
- 大小写:不严格区分大小写,默认大写为程序代码,小写为程序员写的代码
- 语句结束符:每个语句都以;或者\G结束
- 类型:强制数据类型,任何数据都有自己的数据类型
- 逗号:创建表的时候最后一行不需要逗号
3.5总结
4.MySQL表中数据的操作
4.1插入数据
4.1.1指定字段插入
-
insert into tb_name(field_name) values(field_values);
insert into course(id) values(2);
4.1.2全字段插入
-
insert into tb_name values(all_values);
insert into course values(1,'python');
4.1.3多行插入
-
insert into tb_name(field_name) values(value_1),(value_2),…;
insert into course(id,name) values(3,'web'),(4,'java');
4.2查询数据
4.2.1指定字段查询
-
select field_names from tb_name;
select id from course;
4.2.2全字段查询
-
select * from tb_name;
select * from course;
4.2.3带条件的查询
-
select field_names from tb_name where conditions;
select name from course where id<5;
4.3修改数据
4.3.1修改所有数据
-
update tb_name set field_1=value_1;
update course set name='Android';
4.3.2修改多个
-
update tb_name set field_1=value_1,field_2=value_2,…;
update course set name='Android1',id=2;
4.3.3修改满足条件的数据
- update tb_name set field_1=value_1 where confitions;
update course set name='Android' where id=3;
注意:一定要写where条件,不然会修改表中全部数据
4.4删除数据
4.4.1删除表中所有数据
-
delete from tb_name;
delete from course;
4.4.2删除表中满足条件的数据
- delete from tb_name where conditions;
delete from course where id=2;
注意:一定要写where条件,不然会删除表中全部数据