一. 登录mysql
后端开发中,最常用的关系型数据库可能就是mysql了,在linux环境或本地开发环境中,不使用第三方软件时,可直接登录到mysql查看数据表等信息,也可以进行sql的调优,测试等。
linux中,可使用ps -ef | grep mysql查看mysql的安装地址,之后c d至对应mysql安装目录下的bin目录,使用登录命令 mysql -h localhost -u root -p 回车之后输入密码,即可进入mysql。
windows环境使用win + R使用运行命令,其它操作与linux相同。
二. 常用命令
-
show databases; 查看数据库列表
-
create database data_name; # 创建数据库
-
use data_num; # 进入对应数据库
-
show tables; # 查看当前数据库的所有数据表
-
CURD操作; # 使用原生的sql语句即可,例如
创建表:create table test (id int not null primary key auro_increment comment "this is id", name varchar(50) not null default '' comment "this is name", age tinyint(1) not null default 0 comment "this is age");
插入数据:insert into test (name, age) values ('lilei', 12), ('hanmeimei,13);
更新数据:update test set (name = 'jack', age = 18) where id = 1;
查询数据:select * from test where id = 1;
删除数据:delete from test where id = 1;
-
查看数据表的结构
方法一:describe test; # field 列名type 插入数据类型 null 是否为非空约束 no说明不能为空。 key: 主键约束或外键约束 extra 额外信息
方法二:show create table test\G; 查看table表的创建语句。此处可不加\G,加上之后看起来条理更清晰点。
-
查看sql语句执行情况
explain select * from test where id = 1; 可以看到是否使用索引等信息。
-
数据表字段修改,即alter table
添加字段:alter table test add column comment text comment "this is comment" after column name;
删除字段:alter table test drop comment;
重命名字段:alter table test change age ages tinyint(1);
修改字段类型:alter table test change name char(50);
ps. change用来字段重命名,不能修改字段类型和约束; modify不用来字段重命名,只能修改字段类型和约束;
-
复制表结构
仅复制表结构,不复制表内容 create table test1 like test;
仅复制表内容,不复制表结构 create table test2 as select * from test;