1. 程式人生 > >Mysql資料庫的基本操作--資料庫,資料表,資料的基本操作

Mysql資料庫的基本操作--資料庫,資料表,資料的基本操作

- -資料庫的操作

  1. 連結資料庫:mysql -u使用者名稱 -p 密碼
  2. 退出資料庫:exitquitctrl+d
  3. 檢視所有的資料庫:show databases; (注意命令後面要加分號 ;)
  4. 顯示時間:select now();
  5. 顯示資料庫版本:select version();
  6. 資料庫建立:create database 資料庫名;(不指定編碼,預設是latin,儲存中文會有問題)
  7. 資料庫建立:create database 資料庫名 charset=utf8; (指定編碼為utf8)
  8. 檢視建立的資料庫 :show create database 資料庫名;
  9. 刪除資料庫:drop database 資料庫名;
  10. 使用資料庫:use database;
  11. 檢視當前使用的資料庫:select database();

- -資料表的操作

  1. 檢視當前資料庫的所有資料表:show tables;

  2. 建立資料表:create table 表名(欄位1 型別 約束,欄位2 型別 約束);
    比如:
    在這裡插入圖片描述

  3. 查看錶結構 :desc 表名;

  4. 修改表字段–表字段的新增:alter table 表名 add 欄位名 型別/約束;

  5. 修改表字段–表字段變更(欄位名不修改,改型別/約束):alter table 表名 modify 欄位名 新型別/約束;

  6. 修改表字段–表字段變更(欄位名修改):alter table 表名 modify 新欄位名 型別/約束;

  7. 修改表字段–表字段刪除:alter table 表名 drop 欄位名;
    表字段修改案例:
    在這裡插入圖片描述

  8. 資料表刪除:drop table 表名;

  9. 檢視資料表建立結構:show create table 表名;

- -資料操作curd

㈠增加:

  1. 全列插入:insert into 表名 values();
    比如:insert into students values(0, “小花”, 20, “女”, 1, “1990-01-01”);
  2. 部分插入:insert into 表名 (欄位1,欄位2 ...) values(值1,值2...);

    比如: insert into students (name, gender) values (“小喬”, 2);
  3. 多行插入:
    ①:全列多行插入: insert into 表名 values (資料1), (資料2);
    ②:部分多行插入:insert into 表名 (欄位1,欄位2..) values(資料1 ),( 資料2);
    比如
    部分:insert into students (name, gender) values (“大喬”, 2),(“貂蟬”, 2);
    全列:insert into students values(default, “西施”, 20, “女”, 1, “1990-01-01”), (default, “王昭君”, 20, “女”, 1, “1990-01-01”);

㈡修改

update 表名 set 欄位名=值1,欄位名=值2...where 條件;

比如
在這裡插入圖片描述

㈢查詢

  1. 查詢所有:select * from 表名;
  2. 指定條件查詢: select * from 表名 where 條件;
    在這裡插入圖片描述
  3. 指定查詢列:select 欄位名 from 表名;
    在這裡插入圖片描述
    指定別名:
    在這裡插入圖片描述

㈣刪除

1.【物理刪除】 清空資料表:delect from 表名;(不建議使用,會刪除所有資料)
2. 【邏輯刪除】使用一個欄位來標識該資訊無法使用:表新增一個is_delete欄位 bit 型別(0表示未刪除,1表示刪除)default 0

拓展:詳細的查詢方式可參考Mysql資料庫查詢方法大全