數(shù)據(jù)庫筆記

最基本數(shù)據(jù)庫MYSQL常識(shí):

數(shù)據(jù)庫的操作主要包括

  • 數(shù)據(jù)庫的操作,包括創(chuàng)建、刪除
  • 表的操作,包括創(chuàng)建、修改、刪除
  • 數(shù)據(jù)的操作,包括增加、修改、刪除、查詢,簡稱crud字段類型

mysql中數(shù)據(jù)類型常用的幾種

  • 數(shù)字:int,decimal
  • 字符串:varchar,text
  • 日期:datetime
  • 布爾:bit

約束

  • 主鍵primary key   可理解為給表中 每行數(shù)據(jù) 添加一個(gè)獨(dú)特id
  • 非空not null   不允許該字段為null,也就給表加數(shù)據(jù)時(shí)不能為空
  • 惟一unique  保證各行在該索引上的值不為null
  • 默認(rèn)default
  • 外鍵foreign key

基本命令

  1. 登陸數(shù)據(jù)庫
    登陸終端輸入
    mysql -uroot -p
    回車后輸入密碼
    退出登錄
    exit
  2. 遠(yuǎn)程連接
    mysql -hip IP地址 -uroot -p

數(shù)據(jù)庫操作

  1. 創(chuàng)建數(shù)據(jù)庫
    create database 數(shù)據(jù)庫名 charset=utf8;
  2. 刪除數(shù)據(jù)庫
    drop database 數(shù)據(jù)庫名;
  3. 切換數(shù)據(jù)庫
    use 數(shù)據(jù)庫名;
  4. 查看當(dāng)前選擇的數(shù)據(jù)庫
    select database();

表操作

  1. 查看當(dāng)前數(shù)據(jù)庫中所有表
    show tables;
  2. 創(chuàng)建表
    auto_increment表示自動(dòng)增長
    create table 表名(列及類型)
    primary key 表示主鍵
    如:
    其中表名 students  id字段設(shè)置為int類,自動(dòng)增長(例如id第一行為1,第二行會(huì)自動(dòng)增長為2),主鍵(唯一標(biāo)識(shí))
create table students(
id int auto_increment primary key,
sname varchar(10) not null
);
  1. 修改表
alter table 表名 add|change|drop 列名 類型;
如:
alter table students add birthday datetime;
刪除表
drop table 表名;
查看表結(jié)構(gòu)
desc 表名;
更改表名稱
rename table 原表名 to 新表名;
查看表的創(chuàng)建語句
show create table '表名';

數(shù)據(jù)操作

  1. 查詢
    select * from 表名
  2. 增加
    全列插入insert into 表名 values(列1值,列2值...)(...) 每個(gè)括號(hào)代表一個(gè)樣本即每行
    缺省插入:insert into 表名(列1,...) values(值1,...)
    同時(shí)插入多條數(shù)據(jù):insert into 表名 values(...),(...)...;
    或insert into 表名(列1,...) values(值1,...),(值1,...)...;
    主鍵列是自動(dòng)增長,但是在全列插入時(shí)需要占位,通常使用0,插入成功后以實(shí)際數(shù)據(jù)為準(zhǔn)
  3. 修改
    update 表名 set 列1=值1,... where 條件
  4. 刪除
    delete from 表名 where 條件
  5. 邏輯刪除,本質(zhì)就是修改操作update
    alter table students add isdelete bit default 0;
  6. 如果需要?jiǎng)h除則
    update students isdelete=1 where ...;

備份與恢復(fù)

  1. 數(shù)據(jù)備份
    進(jìn)入超級(jí)管理員
    sudo -s
    進(jìn)入mysql庫目錄,主要看你要備份數(shù)據(jù)庫在哪
    cd /var/lib/mysql
    運(yùn)行mysqldump命令
    mysqldump –uroot –p 數(shù)據(jù)庫名 > ~/Desktop/備份文件.sql;
    按提示輸入mysql的密碼

  2. 數(shù)據(jù)恢復(fù)
    連接mysql,創(chuàng)建數(shù)據(jù)庫
    退出連接,執(zhí)行如下命令
    mysql -uroot –p 數(shù)據(jù)庫名 < ~/Desktop/備份文件.sql
    根據(jù)提示輸入mysql密碼

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容