数据库命令: show databases; #查看当前mysql都有那些数据库 create database 数据库名 #创建文件夹 use 数据库名; #选中数据库,进入目录 show tables; #查看当前数据库中有哪些表 create table 表名(id int,name varchar(20),pwd varchar(64)); #创建数据库表 select * from 表名; #查看表中所有数据 insert into 表名(id,name,pwd) values(1,'alex','123'); #插入数据
进入数据库:mysql -u root -p(或mysql -u root -h 127.0.0.1 -p) -h 127.0.0.1 没有的话会自动默认为localhost root用户是原本数据库mysql中user表有的,要创建用户、删除用户等操作要用用户管理特殊命令。 最高管理员(root用户): 创建用户: create user '用户名'@'IP地址' identified by '密码'; 删除用户:drop user '用户名'@'IP地址'; 修改用户:rename user '用户名'@'IP地址';to '新用户名'@'IP地址';; 修改密码:set password for '用户名'@'IP地址'=Password('新密码')
如果创建新用户root1,被授权,那么就要登录root账户为root1设置权限。
grant insert on 数据库.表名 to root1@localhost;
innodb引擎 支持事物操作(一个数据库给另一个账户转账过程中突然数据库链接中断,那么再连接上数据库时钱会回到原有账户) 创建表(设置可为空或不可为空,设置默认值) create table 表名( id int not null default 2, num int null)engine=innodb default charset=utf8; #innodb引擎支持外键
1.创建表(设置自增列(需主键),插入数据时只用给字段name赋值) create table 表名( id int not null auto_increment primary key name varchar(20))
两列可以组成一个主键(每个主键不相同): create table student( name varchar(10) not null, num int not null, age int, primary key(name,num))
2.删除表:drop table 表名;
3.清空表:delete from 表名/truncate table 表名(删除后自增回到原点)
4.修改表 添加列:alter table 表名 add 列名 类型 删除列:alter table 表名 drop cloumn 列名 修改列:alter table 表名 modify column 列名 类型 alter table 表名 change 原列名 新列名 类型 添加主键:alter table 表名 add primary key(列名) 删除主键:alter table 表名 drop primary key alter table 表名 modify 列名 int,drop primary key;
5.表内容操作(将表2的两列内容插入到表一的两列中) 增:insert into 表1 (列名,列名) select(列名,列名)from 表2 删:delete from 表 delete from 表 where id=1 and name='alex' 改:update 表 set name ='alex' where id>1 查:select * from 表 select * from 表 where id>1
设置外键: 1.(两张表先前创建好的) alter table 1表名 add constraint 外键名(可随机) foreign key 1表名(字段名) references 2表名(2表主键字段名); 2.(在创建两张表的同时创建外键) create table color( id int not null primary key, name char(15) not null) create table fruit( id int not null primary key, smt char(23) null, color_id int not null, constraint fk_cc foreigner key (color_id) references color(id)) 连表操作 select * from a,b where a.x=b.o select * from a left join b on a.x=b.o