连接MySQL
-
Linux终端下,运行以下命令,回车后输入密码
mysql -uroot -p
-
Windows PowerShell下,运行以下命令,回车后输入密码
mysql -u root -p
-
登录成功后,输入以下命令查看效果
-
查看版本
select version();
-
显示当前时间
select now();
-
-
退出登录
quit 和 exit 或 ctrl+d
数据库操作
-
查看所有数据库
show databases;
-
使用数据库
use 数据库名; eg: use python;
-
创建数据库
create database 数据库名 charset=utf8; eg: create database python charset=utf8;
-
删除数据库
drop database 数据库名; eg: drop database python;
数据表操作
-
查看当前数据库中所有表
show tables;
-
查看表结构
desc 表名; eg: desc python;
-
创建表
create table 表名( 字段1 数据类型 约束, 字段2 数据类型 约束, 字段3 数据类型 约束, ...... 字段N 数据类型 约束, );
-
例1:创建班级表
create table classes( id int unsigned auto_increment primary key not null, name varchar(10) );
-
例2:创建学生表
create table students( id int unsigned auto_increment primary key not null, name varchar(20) default '', age tinyint unsigned default 0, gender enum('male', 'female', 'secret'), height decimal(5,2), cls_id int unsigned default 0 );
-
-
删除表
drop table 表名; eg: alter table students;
-
查看表的创建语句
show create table 表名; eg: show create table classes;
字段操作
- 格式
alter table 表名 具体字段增删改查
-
添加字段
alter table 表名 add 字段名 数据类型及约束; eg: alter table students add birthday datetime;
-
修改字段
-
重命名
alter table 表名 change 原字段名 新字段名 数据类型及约束; eg: alter table students change birthday birth datetime not null;
-
不重命名
alter table 表名 modify 字段名 数据类型及约束; eg: alter table students modify birth date not null;
-
-
删除字段
alter table 表名 drop 字段名; eg; alter table students drop birthday;
记录增删改查(curd)
CURD:创建(Create)、更新(Update)、读取(Retrieve)和删除(Delete)
查询
-
查询所有列
select * from 表名; eg: select * from classes;
-
查询指定列
select 列1, 列2, ... from 表名; eg: select id, name from classes;
增加
-
全列插入:值的顺序与表中字段的顺序对应
说明:主键列是自动增长,但是在全列插入时需要占位,通常使用0或者default或者null来占位,插入成功后以实际数据为准insert into 表名 values(...); eg: insert into students values(0, '学生', 1, '地点', '2016-1-2');
-
部分列插入:值的顺序与给出的列顺序对应
insert into 表名(列1, ...) values(值1, ...); eg: insert into students(name, hometown, birthday) values('学生', '地点', '2016-3-2');
-
多行插入:一次性插入多行数据,减少与数据库通信
-
全列
insert into 表名 values(值1, ...); eg: insert into classes values(0, 'python1'), (0, 'python2');
-
部分列
insert into 表名(列1, ...) values(值1, ...), (值2, ...)...; eg: insert into students(name) values('name1'), ('name2'), ('name3');
-
修改
-
修改记录
update 表名 set 列1=值1, 列2=值2, ... where 条件; eg: update students set gender=0, hometown='Beijing' where id=5;
删除
-
物理删除
delete from 表名 where 条件; eg: delete from students where id=5;
-
逻辑删除
本质是修改操作update students set isdelete=1 where id=1;
数据备份&恢复
-
数据库备份
mysqldump -uroot -p 数据库名 > python.sql; # 根据提示输入mysql的密码
-
恢复
-
连接mysql,创建新的数据库
-
退出连接,执行以下命令
mysql -uroot -p 新数据库名 < python.sql; # 根据提示输入mysql密码
-