數(shù)據(jù)庫操作
鏈接數(shù)據(jù)庫
mysql -uroot -pmysql
退出數(shù)據(jù)庫
exit
查看所有創(chuàng)建數(shù)據(jù)庫
show databases;
查看當前正在使用的數(shù)據(jù)庫
select database();
使用數(shù)據(jù)庫
use 數(shù)據(jù)庫名;
sql語句最后需要有;結尾
顯示數(shù)據(jù)庫版本
select version();
顯示時間
select now();
創(chuàng)建數(shù)據(jù)庫demo
create database demo;
指定字符集
create database demo charset=utf8; #必須是utf8字符集
查看數(shù)據(jù)庫的創(chuàng)建語句
show create database demo;
刪除數(shù)據(jù)庫
drop database demo;
數(shù)據(jù)表操作
查看當前數(shù)據(jù)庫中所有表
show tables;
創(chuàng)建表
unsigned 表示沒有符號旱函,沒有負數(shù)待秃,
auto_increment表示自動增長
創(chuàng)建一個學生的數(shù)據(jù)表(id,name,age,high,gender,cls_id)
create table 數(shù)據(jù)表名字(字段 類型 約束[,字段 類型 約束]);
多個約束 不分先后順序
enum 表示枚舉
最后一個字段不用添加逗號
create table students(字段名 字段類型 字段約束);
create table students(
id int unsigned primary key auto_increment,
name varchar(15) not null,
age tinyint unsigned default 0,
high decimal(5,2) default 0.0,
gender enum('男','女','中性','保密') default '保密',
cls_id int unsigned not null
);
查看表的創(chuàng)建語句
show create table students;
查看表結構
desc students;
修改表結構 alter add/modify/change
修改表-添加字段
alter table 表名 add 列名 類型/約束缘薛;
例如:添加生日信息
alter table students add birthday datetime default "2011-11-11 11:11:11";
修改表-修改字段:不重命名版
alter table 表名 modify 列名 類型及約束;
例如:將生日信息里的時分秒去掉
alter table students modify birthday date default "2011-11-11";
修改表-修改字段:重命名版
alter table 表名 change 原列名 新列名 類型及約束;
例如:將生日birthday 改成birth
alter table students change birthday birth date default "2011-11-11";
修改表-刪除字段
alter table students drop birth;
刪除表
drop table students;
數(shù)據(jù)增刪改查(curd)
增加 insert
insert [into] 表名 values (值1检诗,值2糯累,...);
全列插入 值和表的字段順序一一對應
占位符:只有主鍵字段才有占位符的概念 0栗弟,default, NULL
全列插入在實際開發(fā)中用的不多 如果表結構一旦發(fā)生變化吐葵,全列茶入就會報錯
例如:
insert into students values (0,'小喬', 18, 180.00, '女', 2);
insert into students values(default,'大喬', 19, 180.00, '女', 2);
指定列插入
值和列一一對應
insert into 表名 (列1,...) values (值1,...)
例如:
insert into students (name, high, gender cls_id) values ('張飛', 190.00, '保密', 1);
多行插入 批量插入
insert into 表名 (列1,...) values (值1,...), (值2,...),...;
例如:
insert into students values (0, '小喬', 18, 180.00, '女', 2),
(0, '甄姬', 20, 170.00, '女', 2);
insert into students (name, high, gender, cls_id) values ('張飛', 1900.00, '保密', 1),
('關羽', 1900.00, '男', 1);
修改 update
where 表示修改的范圍
update 表名 set 列1=值1, 列2=值2... [where 條件]
沒有where進行條件限制就是全表更新
例如:
update students set age = 20;
刪除 delete
物理刪除
delete from 表名 [where 條件判斷]
delete from students where id = 5;
邏輯刪除
查詢基本使用select
查詢所有列
select * from 表名;