DDL操作資料庫
建立資料庫
- 點選Navicat裡的建立查詢。
- sql語句中注釋為:
- 指令:
- create database 資料庫名; #建立指定名稱的資料庫
- create database 資料庫名 character set 字元集; # 建立指定名稱的資料庫,并指定字元集(一般為utf8)
- use 資料庫名; # 切換資料庫
- select database(); #查詢目前所使用的的資料庫*
- show databases; # 查詢mysql中有哪些資料庫
- show create database db1; # 檢視資料庫定義資訊
修改資料庫
- 修改資料庫字元集
- 指令:
- alter database 資料庫名 character set 字元集; #修改指定資料庫的字元集
删除資料庫
- 指令 :
- drop database 資料庫名; # 從mysql中永久的删除某個資料庫
DDL操作資料表
- 一個資料庫中有n個表,表中又有字段(列),在建表的是就需要定義好字段(指定字段屬性------>字段屬性類型+字段長度等)
建立表
- 文法格式:
-
create table 表名(
字段名稱1 字段類型(長度)
字段名稱2 字段類型 注:最後一列不要加逗号
);
-
/*需求:
表名:category
表中字段:
分類id:cid,整型
分類名稱:cname,為字元型類型,指定長度為20
*/
create table category(
-- 定義字段資訊
cid int,
cname varchar(20)
);
/*
需求:建立測試表
表名:test1
表中字段:
測試id:tid,整型
測試時間:tdate,為年月日的日期類型
*/
create table test1(
tid int,
tdate DATE
);
/*
需求:快速建立一個表結構相同的表(複制表結構,不複制資料)
文法格式:
Create table 新标名 like 舊表名;
*/
create table test2 like test1;
-- 檢視表結構
desc test2;
查詢表
- 檢視目前資料庫中有哪些資料表
-
show tables;
- 檢視目前資料表的結構
-
desc test2;
- 檢視建立表的sql語句
-
show create table test2;
删除表
-- 删除資料庫/表用drop
drop table test1;
-- 判斷存在表再删除
drop table if exists test1;
修改表
- 修改表名
-
rename table 舊表名 to 新表名
rename table category to category1 #将表category改為category1
- 向表中添加列,關鍵字ADD
- 修改表中列的資料類型或長度,關鍵字MODYFI
- 修改列名稱,關鍵字CHANGE
- 删除列,關鍵字DROP