準備工作
在 windows 和 Ubuntu 安裝 MySQL。具體安裝步驟可去 csdn 論壇查詢。
命令行腳本
數據庫的操作
- 連接數據庫
注意:sql 語句最後需要以分號 ;結尾
mysql -uroot -p;
輸入密碼即可進入數據庫。
- 退出數據庫
qiut,exit,ctrl + d;
- 查看所有數據庫
show databases;
- 使用數據庫
use 數據庫名;
- 查看當前使用的數據庫
select database();
- 顯示數據庫版本
select version();
- 創建數據庫
create database demo charset=utf8;
需要知道字符集,注意不是 utf-8;
- 查看數據庫的創建語句
show create database demo;
- 刪除數據庫
drop database demo;
- 查看幫助文檔
sql中的幫助文檔如何使用?
使用 ? 獲取幫助信息
? functions; 查看函數的幫助文檔
數據表的操作
- 查看當前數據庫中所有表
show tables;
- 創建表
auto_increment 表示自動增長
創建一個學生的數據表(id name age high gender cls_id)
create table 數據表名字 (字段名 類型 約束[, 字段 類型 約束]);
多個約束 不分先後順序
enum 表示枚舉 男: 原始值 會有一個枚舉值(從1開始)對應
最後一個字段不要添加逗號
unsigned表示無符號(只有正數, 沒有負數)
- 創建 students 表
create table students (
id int unsigned primary key auto_increment not null,
name varchar(15) not null,
age tinyint unsigned default 18,
height decimal(5,2) default 0,
gender enum("男","女","中性","保密") default "保密",
cls_id int unsigned default 0,
is_delete bit default 0
);
- 插入數據(後面要用)
insert into students values
(0,'小明',18,180.00,2,1,0),
(0,'小月月',18,180.00,2,2,1),
(0,'彭于晏',29,185.00,1,1,0),
(0,'劉德華',59,175.00,1,2,1),
(0,'黃蓉',38,160.00,2,1,0),
(0,'鳳姐',28,150.00,4,2,1),
(0,'王祖賢',18,172.00,2,1,1),
(0,'周杰倫',36,NULL,1,1,0),
(0,'程坤',27,181.00,1,2,0),
(0,'劉亦菲',25,166.00,2,2,0),
(0,'金星',33,162.00,3,3,1),
(0,'靜香',12,180.00,2,4,0),
(0,'郭靖',12,170.00,1,4,0),
(0,'周杰',34,176.00,2,5,0);
- 查看創建表的語句
show create table students;
- 查看錶結構
desc students;
- 修改表結構
- 修改表-添加字段
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 原列名 新列名 類型及約束;
alter table students change birthday birth date default "2011-11-11";
- 修改表-刪除字段
alter table students birth;
- 刪除表
drop table students;
數據增刪改查(curd)
- 增加 insert
- - 全列插入 值和表的字段的順序一一對應
- insert into 表名 values (值1,…)
- 主鍵字段的佔位操作: 0, NULL, Default
- 在sql中枚舉的下標默認從1開始
- 在實際開發中全列插入使用的不多: 如果表結構發生修改(增加或者刪除字段) 全列插入的sql語句就會出錯
insert into students values (0,"小喬",18,180.00,"女",2);
insert into students values (NULL,"小喬",18,180.00,"女",2);
insert into students values (NULL,"大喬",18,180.00,2,2);
錯誤: insert into students values (Default,"虞姬",18,180.00,10,2,10);
- 指定列插入
insert into 表名 (列1,...) values(值1,...)
insert into students (name, gender, cls_id) values ("魯班",1,1);
- 多行插入 批量插入
insert into 表名(列1,...) values (值1,...),(值1,...),...
insert into students (name, gender, cls_id) value ('wasp', '女', '2'),('vae', '男', '1');
- 刪除
- 物理刪除
DELETE FROM tbname [where 條件判斷]
delete from students where id = 5;
- 邏輯刪除:
標識一條記錄是否被刪除
update students set is_delete = 1 where id = 4;
查詢有哪些學生沒有被刪除
select * from students where is_delete = 0;
- 修改
where 表示修改的範圍
update 表名 set 列1=值1,列2=值2... where 條件
全表更新, 一定不要使用整表更新
update students set age = 20;
指定範圍更新
update students set age = 20 where id = 3;
sql中,通過一個等於號表示相等
閱讀更多 waspvae 的文章