MySQL常用指令:
1.命令行啟動mysql :
c:/>mysql -h hostname -u root -p
或
c:/>mysql -u root -p root (密碼)
或
c:/>mysql -uroot -proot (密碼)
(windows平臺 需要將mysql加入Path環(huán)境變量中)
(-p 后接密碼后回車 也可以 回車后輸入密碼)
若連接本地數(shù)據(jù)庫 -h hostname 改為 -h localhost 或者省略-h hostname(即為mysql -u root -p)
若連接遠(yuǎn)端服務(wù)器的數(shù)據(jù)庫 -h hostname 改為 -h + 192.168.X.X (遠(yuǎn)程服務(wù)器的IP地址)
2.查看mysql的幫助:
c:/> mysql --help
3.查看現(xiàn)在時間:
select current_date;
select now();
mysql是一個數(shù)據(jù)庫軟件 數(shù)據(jù)庫是表的集合
mysql里面可以有很多數(shù)據(jù)庫(可以理解為很多表的集合)
4.顯示mysql里面有多少數(shù)據(jù)庫:
show databases;
5 sql注釋語句:
mysql > -- 注釋內(nèi)容
注意 -- 和注釋之間有個空格卜朗!
6 創(chuàng)建數(shù)據(jù)庫:
create database 數(shù)據(jù)庫名稱
mysql > create database mybase;
7 刪除數(shù)據(jù)庫:
drop database 數(shù)據(jù)庫名稱:
mysql > drop database mybase;
8 使用指定的數(shù)據(jù)庫:
use + 指定的數(shù)據(jù)庫名稱
mysql > use myhive;
9 指定數(shù)據(jù)庫后顯示數(shù)據(jù)庫中所有表:
mysql > show tables;
Empty set 標(biāo)識表空
10 在數(shù)據(jù)庫中創(chuàng)建表:
11 查看數(shù)據(jù)表:
mysql > show create table test;
mysql > desc test;
mysql > describe test;
(test 為一個表名)
查看表結(jié)構(gòu):
12 刪除表:
mysql > drop table test;
13 查詢表數(shù)據(jù):
mysql > select * from test;
(全字段 全表掃描)
或者:
mysql > select id,name from test;
(部分字段查詢 投影查詢)
條件查詢 查id>3的字段:
其他查詢注意:
14 插入記錄:
mysql > insert into test(id,name,age) values(1,'wang',23);
或插入部分字段數(shù)據(jù):
mysql > insert into test(id,name) values(1,'wang');
若插入全部字段可以簡寫:
mysql > insert into test values(1,'wang',59);
15 更新記錄:
mysql > update test set grade=11 where id = 2;
16 刪除記錄:
mysql > delete from test where id=1;
注意蟀伸,若:
mysql > delete from test;
則會把所有記錄刪除莽使,要謹(jǐn)慎蜻懦!
小總結(jié):
CRUD:
create:
insert into table_name(field_name,...) values(value,...);
retrieve:
select id ,... from table_name where id=xxx,...;
update:
update table_name set id=xxx,... where id=xxx,...;
delete:
delete from test where ...;
MySQL約束:
1 primary key 主鍵
主鍵特點:不為null 不能重復(fù)
mysql > create table test(id int primary key,...);
2 自增
mysql > create table test(id int primary key auto_increment,...);
自增是查詢到最大值后+1
3 不能為空 not null:
mysql > create table test(id int primary key auto_increment, name varchar(20) not null, age int);
4 帶條件創(chuàng)建 刪除:
// 帶條件創(chuàng)建
mysql > create database if not exists itcast;
mysql > create table if not exists test;
// 帶條件刪除
mysql > drop database if exists itcast;
mysql > drop table if exists test;
設(shè)一個字段為空值:
update test set name=null where id=3;
注意:需要在設(shè)計表中允許name字段為空 才能在客戶端用指令設(shè)置空值
設(shè)置字段為null后 我們來查詢?yōu)閚ull的字段:
可見查詢 null 比較特殊 不能用:
mysql > ... where name=null;
而應(yīng)該:
mysql > ... where name is null;
來看個特Null情況:
來個段子:
比如你問我:“那個人叫什么名字”得封?
我說:“不知道”甸陌。
不知道 可能是那個人叫不知道湘捎,也可能是我真不知道钟沛。
這就是兩種Null的區(qū)別...
所以要特別注意Null
拓展:
使用MySQL命令行執(zhí)行sql腳本:
mysql > source d:/java/xxx.sql;
更多內(nèi)容下載ppt學(xué)習(xí):
http://pan.baidu.com/s/1hs3QDvQ