## 向表中插入數據
insert 語句可以用來將一行或多行數據插到數據庫表中, 使用的一般形式如下:
~~~
insert [into] 表名 [(列名1, 列名2, 列名3, ...)] values (值1, 值2, 值3, ...);
~~~
其中 [] 內的內容是可選的, 例如, 要給 samp_db 數據庫中的 students 表插入一條記錄, 執行語句:
~~~
insert into students values(NULL, "王剛", "男", 20, "13811371377");
~~~
按回車鍵確認后若提示 Query Ok, 1 row affected (0.05 sec) 表示數據插入成功。 若插入失敗請檢查是否已選擇需要操作的數據庫。
有時我們只需要插入部分數據, 或者不按照列的順序進行插入, 可以使用這樣的形式進行插入:
~~~
insert into students (name, sex, age) values("孫麗華", "女", 21);
~~~
## 查詢表中的數據
select 語句常用來根據一定的查詢規則到數據庫中獲取數據, 其基本的用法為:
~~~
select 列名稱 from 表名稱 [查詢條件];
~~~
例如要查詢 students 表中所有學生的名字和年齡, 輸入語句 select name, age from students; 執行結果如下:
~~~
mysql> select name, age from students;
+--------+-----+
| name | age |
+--------+-----+
| 王剛 | 20 |
| 孫麗華 | 21 |
| 王永恒 | 23 |
| 鄭俊杰 | 19 |
| 陳芳 | 22 |
| 張偉朋 | 21 |
+--------+-----+
6 rows in set (0.00 sec)
mysql>
~~~
也可以使用通配符 * 查詢表中所有的內容, 語句: select * from students;
## 按特定條件查詢:
where 關鍵詞用于指定查詢條件, 用法形式為:
~~~
select 列名稱 from 表名稱 where 條件;
~~~
以查詢所有性別為女的信息為例, 輸入查詢語句:
~~~
select * from students where sex="女";
~~~
where 子句不僅僅支持 "where 列名 = 值" 這種名等于值的查詢形式, 對一般的比較運算的運算符都是支持的, 例如 =、>、=、
**示例:**
查詢年齡在21歲以上的所有人信息:
~~~
select * from students where age > 21;
~~~
查詢名字中帶有 "王" 字的所有人信息:
~~~
select * from students where name like "%王%";
~~~
查詢id小于5且年齡大于20的所有人信息:
~~~
select * from students where id20;
~~~
## 更新表中的數據
update 語句可用來修改表中的數據, 基本的使用形式為:
~~~
update 表名稱 set 列名稱=新值 where 更新條件;
~~~
**使用示例:**
將id為5的手機號改為默認的"-":
~~~
update students set tel=default where id=5;
~~~
將所有人的年齡增加1:
~~~
update students set age=age+1;
~~~
將手機號為 13288097888 的姓名改為 "張偉鵬", 年齡改為 19:
~~~
update students set name="張偉鵬", age=19 where tel="13288097888";
~~~
## 刪除表中的數據
delete 語句用于刪除表中的數據, 基本用法為:
~~~
delete from 表名稱 where 刪除條件;
~~~
**使用示例:**
刪除id為2的行:
~~~
delete from students where id=2;
~~~
刪除所有年齡小于21歲的數據:
~~~
delete from students where age
~~~
刪除表中的所有數據:
~~~
delete from students;
~~~