最基本數(shù)據(jù)庫(kù)MYSQL常識(shí):
數(shù)據(jù)庫(kù)的操作主要包括
- 數(shù)據(jù)庫(kù)的操作,包括創(chuàng)建瓶籽、刪除
- 表的操作匠童,包括創(chuàng)建、修改塑顺、刪除
- 數(shù)據(jù)的操作汤求,包括增加、修改严拒、刪除扬绪、查詢,簡(jiǎn)稱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
基本命令
- 登陸數(shù)據(jù)庫(kù)
登陸終端輸入
mysql -uroot -p
回車后輸入密碼
退出登錄
exit
- 遠(yuǎn)程連接
mysql -hip IP地址 -uroot -p
數(shù)據(jù)庫(kù)操作
- 創(chuàng)建數(shù)據(jù)庫(kù)
create database 數(shù)據(jù)庫(kù)名 charset=utf8;
- 刪除數(shù)據(jù)庫(kù)
drop database 數(shù)據(jù)庫(kù)名;
- 切換數(shù)據(jù)庫(kù)
use 數(shù)據(jù)庫(kù)名;
- 查看當(dāng)前選擇的數(shù)據(jù)庫(kù)
select database();
表操作
- 查看當(dāng)前數(shù)據(jù)庫(kù)中所有表
show tables;
- 創(chuàng)建表
auto_increment表示自動(dòng)增長(zhǎng)
create table 表名(列及類型)
primary key 表示主鍵
如:
其中表名 students id字段設(shè)置為int類挤牛,自動(dòng)增長(zhǎng)(例如id第一行為1,第二行會(huì)自動(dòng)增長(zhǎng)為2)种蘸,主鍵(唯一標(biāo)識(shí))
create table students(
id int auto_increment primary key,
sname varchar(10) not null
);
- 修改表
alter table 表名 add|change|drop 列名 類型;
如:
alter table students add birthday datetime;
刪除表
drop table 表名;
查看表結(jié)構(gòu)
desc 表名;
更改表名稱
rename table 原表名 to 新表名;
查看表的創(chuàng)建語(yǔ)句
show create table '表名';
數(shù)據(jù)操作
- 查詢
select * from 表名
- 增加
全列插入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)增長(zhǎng),但是在全列插入時(shí)需要占位航瞭,通常使用0诫硕,插入成功后以實(shí)際數(shù)據(jù)為準(zhǔn) - 修改
update 表名 set 列1=值1,... where 條件
- 刪除
delete from 表名 where 條件
- 邏輯刪除,本質(zhì)就是修改操作update
alter table students add isdelete bit default 0;
- 如果需要?jiǎng)h除則
update students isdelete=1 where ...;
備份與恢復(fù)
數(shù)據(jù)備份
進(jìn)入超級(jí)管理員
sudo -s
進(jìn)入mysql庫(kù)目錄刊侯,主要看你要備份數(shù)據(jù)庫(kù)在哪
cd /var/lib/mysql
運(yùn)行mysqldump命令
mysqldump –uroot –p 數(shù)據(jù)庫(kù)名 > ~/Desktop/備份文件.sql;
按提示輸入mysql的密碼數(shù)據(jù)恢復(fù)
連接mysql章办,創(chuàng)建數(shù)據(jù)庫(kù)
退出連接,執(zhí)行如下命令
mysql -uroot –p 數(shù)據(jù)庫(kù)名 < ~/Desktop/備份文件.sql
根據(jù)提示輸入mysql密碼