有些時(shí)候我們不得不去用命令行操作mysql數(shù)據(jù)庫(kù),下面是筆者總結(jié)的常見(jiàn)操作命令:
1.連接
? 命令:? mysql -h主機(jī)地址 -u用戶名 -p密碼
? 本地:連接?? cmd進(jìn)入mysql/bin之后, 輸入mysql -uroot -p然后回車(chē) 會(huì)提示你輸入密碼 接著回車(chē)即可(如果密碼為空);
? 遠(yuǎn)程連接:假設(shè)遠(yuǎn)程主機(jī)的IP為:222.222.212.212,用戶名為root,密碼為abcdef。則鍵入以下命令:
???? mysql -h222.222.212.212 ?-uroot? -pabcdef
2.對(duì)數(shù)據(jù)庫(kù)和表的操作
???
???查看用戶擁有權(quán)限的數(shù)據(jù)庫(kù)?:????? show databases;(注意分號(hào))
?
?? 創(chuàng)建數(shù)據(jù)庫(kù)test:? create database testdb;
?? 切換到testdb數(shù)據(jù)庫(kù):?????? use testdb;
?? 刪除數(shù)據(jù)庫(kù)testdb: drop database?testdb;
?? 查看當(dāng)前數(shù)據(jù)庫(kù)中有權(quán)限的表: show tables;
?? 創(chuàng)建表s_position,department,,depart_pos,testtable:
???? create table s_position
???? (
???????? id int not null auto_increment,
???????? name varchar(20) not null default? '經(jīng)理',????????? #設(shè)定默認(rèn)值
???????? description varchar(100),
???????? primary key PK_positon (id)?????????????????????????? ?#設(shè)定主鍵
???? );????
???? create table department
???? (
???????? id int not null auto_increment,
???????? name varchar(20) not null default '系統(tǒng)部',????????? #設(shè)定默認(rèn)值
???????? description varchar(100),
???????? primary key PK_department (id)??????????????????????? #設(shè)定主鍵
???? );
???? create table depart_pos
???? (
???????? department_id int not null,
???????? position_id int not null,
???????? primary key PK_depart_pos (department_id,position_id)? #設(shè)定復(fù)和主鍵
???? );
???? create table testtable
???? (
???????? id int not null auto_increment primary key,???? #設(shè)定主鍵
???????? name varchar(20) not null default '無(wú)名氏',? #設(shè)定默認(rèn)值
???????? department_id int not null,
???????? position_id int not null,
???????? unique (department_id,position_id)????????????? #設(shè)定唯一值
???? );
?? 查看表testtable的結(jié)構(gòu):?? desc testtable;
?? 刪除表testtable:?????
??????? drop table testtable;???????
? 修改表結(jié)構(gòu) 操作數(shù)據(jù)(增,刪,改,查)
???.....(同sql語(yǔ)句,略)
?3. 備份和恢復(fù)
?? 對(duì)數(shù)據(jù)的備份和恢復(fù)命令,在網(wǎng)上有許多種版本,經(jīng)筆者親身測(cè)驗(yàn),下面的命令是可行方法之一:
???
??? 備份數(shù)據(jù)庫(kù)testdb:??
??? 本地:mysqldump -uroot? -pabcdef testdb>e:testdb.sql?
??? 遠(yuǎn)程:mysqldump -h222.222.212.212 -uroot? -pabcdef testdb>e:testdb.sql?
???這里假設(shè)數(shù)據(jù)庫(kù)的用戶名和密碼分別是root和abcdef, 導(dǎo)出到額盤(pán)根目錄下,得到的testdb.sql是一個(gè)sql腳本,不包括建庫(kù)的語(yǔ)句,所以你需要手工創(chuàng)建數(shù)據(jù)庫(kù)下次才可以導(dǎo)入 恢復(fù)數(shù)據(jù)庫(kù)testdb;
??????
???? 恢復(fù)數(shù)據(jù)庫(kù)testdb:??????首先 需要?jiǎng)?chuàng)建一個(gè)空庫(kù)testdb(原因如上);
???? 命令:??
???? 本地:mysql -uroot -pabcdef? testdb<e:testdb.sql????
???? 遠(yuǎn)程:mysql -h222.222.212.212? -uroot -pabcdef? testdb<e:testdb.sql????
???? 后面e:testdb.db代表本地sql文件路徑,如果mysql安裝在本地可以把sql文件考到mysql/bin的安裝目錄下,就不用寫(xiě)路徑了.
注:在網(wǎng)上有些朋友說(shuō),mysql的安裝目錄必須為默認(rèn)目錄(即c:/mysql),否則會(huì)出問(wèn)題,筆者也測(cè)驗(yàn)了一下在安裝d盤(pán)的效果,結(jié)果暫時(shí)沒(méi)有發(fā)現(xiàn)什么問(wèn)題.,這說(shuō)明有時(shí)候命令執(zhí)行異常可能和安裝目錄無(wú)關(guān).^_^