mysql的數據操作
INSERT [INTO] 表名 [(字段名1,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
-
-
全列插入:值的順序與表結構字段的順序完全一一對應
此時 字段名列表不用填寫
insert into 表名 values (...)
例:
insert into students values(0,’郭靖‘,1,'蒙古','2016-1-2');
-
部分列插入:值的順序與給出的列順序對應
此時需要根據實際的數據的特點 填寫對應字段列表
insert into 表名 (列1,...) values(值1,...)
例:
insert into students(name,hometown,birthday) values('黃蓉','桃花島','2016-3-2');
-
上面的語句一次可以向表中插入一行數據,還可以一次性插入多行數據,這樣可以減少與數據庫的通信
-
全列多行插入
insert into 表名 values(...),(...)...;
例:
insert into classes values(0,'python1'),(0,'python2');
-
部分列多行插入
insert into 表名(列1,...) values(值1,...),(值1,...)...;
例:
insert into students(name) values('楊康'),('楊過'),('小龍女');
2 數據修改
UPDATE 表名 SET 字段1名={expr1|DEFAULT} [,col2={expr2|default}] [where 條件判斷]
update 表名 set 列1=值1,列2=值2... where 條件
例:
update students set gender=0,hometown='北京' where id=5;
3 數據刪除
DELETE FROM 表名 [where 條件判斷]
delete from 表名 where 條件
例:
delete from students where id=5;
拋出問題: 上面的操作稱之為物理刪除,一旦刪除就不容易恢復。那么刪除操作有沒有一個類似于回收站一樣的功能,能夠讓用戶選擇清空或者恢復刪除的功能呢?
* 其實刪除文件進入回收站的本質只是在操作系統的幫助下對文件加上了 某個標記,資源管理器中對含有這種標記的文件不會顯示。當從回收站恢復的時候只是移除了加上的標記而已。
-
邏輯刪除,本質就是修改操作
update students set isdelete=1 where id=1;
4 數據查詢
4.1 創建數據庫、數據表
-- 創建數據庫
.
create database python_test_1 charset=utf8;
?
-- 使用數據庫
use python_test_1;
?
-- students表
create table students(
id int unsigned primary key auto_increment not null,
name varchar(20) default '',
age tinyint unsigned default 0,
height decimal(5,2),
gender enum('男','女','中性','保密') default '保密',
cls_id int unsigned default 0,
is_delete bit default 0
);
?
-- classes表
create table classes (
id int unsigned auto_increment primary key not null,
name varchar(30) not null
);
4.2 準備數據
-- 向students表中插入數據
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);
