1 資料庫基本操作? (1) 查看資料庫 show databases; (2)切換到指定的資料庫 use dbname; (3)創建資料庫 create database 庫名 charset=utf8; (4)刪除資料庫 drop database 庫名; 2 數據表基本操作? (1) 查看當前 ...
1 資料庫基本操作?
(1) 查看資料庫
show databases;
(2)切換到指定的資料庫
use dbname;
(3)創建資料庫
create database 庫名 charset=utf8;
(4)刪除資料庫
drop database 庫名;
2 數據表基本操作?
(1) 查看當前庫下所有表
show tables;
*模糊查詢
show tables like 'pattern';
(2)查看表結構
desc 表名;
(3)創建表
方式一:create table [if not exists] 資料庫名.表名( -- 顯示指定資料庫名
欄位名字 數據類型,
欄位名字 數據類型
)[表選項];
if not exists : 如果表不存在才創建。
表選項:字元集、校對集、存儲引擎
方式二:use 資料庫名;
create table [if not exists] 表名( -- 先進入資料庫,後面的所有操作都作用於這一個資料庫中
欄位名字 數據類型,
欄位名字 數據類型
)[表選項];
ex:
create tbname(
id int unsingned primary key auto_increment not null,
name varchar(20) default '',
age int unsingned default 0,
height decimal(3,2) default 1.8,
gender enum('男','女') default 男,
);
說明:UNSIGNED屬性就是將數字類型無符號化
ENUM是枚舉類型,它雖然只能保存一個值,卻能夠處理多達65535個預定義的值。(慎用 https://www.sohu.com/a/226090587_820120)
(4) 添加欄位
alter table 表名 add 欄位名稱 類型;
ex:
alter table table1 add transactor varchar(10) not Null;
ex:增加主鍵子段
alter table table1 add id int unsigned not Null auto_increment primary key
* 查看欄位信息
show columns from/describe/desc 表名;
註:結尾處的分號可用\g或\G代替,用\g與分號效果相同,用\G時行變列,列變行,在某些時候可以提高閱讀性;
(5)修改某個表的欄位類型及指定為空或非空
alter table 表名 change 欄位名稱 欄位類型 [是否允許非空];
alter table 表名 modify 欄位名稱 欄位類型 [是否允許非空];
(6)修改某個表的欄位名稱及指定為空或非空
alter table 表名稱 change 欄位原名稱 欄位新名稱 欄位類型 [是否允許非空];
alter table 舊表名 rename to 新表名;
(7)如果要刪除某一欄位
alter table 表名 DROP 欄位名;
(8)刪除表
drop table 表名;
(9)查看表的創建語句
show create table 表名;
3 數據 增 刪 改?
(1) 增加數據
*單條全部列插入的方式
insert into 表名 value();
*單條部分列插入的方式
insert into 表名(列1,...) value();
*多條數據部分列插入的方式
insert into 表名(列1,....) value(),...;
(2)刪除某條數據
delete from 表名 where 條件;
(3)改某條數據
update 表名 set 列1=值,列2=值,... where 條件;