2010年7月19日 星期一

MySQL5資料如何以CSV格式做EXPORT和IMPORT

[MySQL5]
資料庫的資料,匯出成一個 CSV 檔案!
SELECT * INTO OUTFILE '/the/path/of/testdata.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' FROM testdata WHERE 1 ;

把 CSV 檔案,匯入MySQL5資料庫裡!
LOAD DATA LOCAL INFILE '/the/paht/of/testdata.csv' INTO TABLE testdata FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' ;


另一範例:
如果有指定欄位的話!
[EXPORT]
SELECT (uniqName, uniqCity, uniqComments) INTO OUTFILE 'testdata.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' FROM testdata WHERE 1 ;
[IMPORT]
LOAD DATA LOCAL INFILE 'testdata.csv' INTO TABLE testdata FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' (uniqName, uniqCity, uniqComments) ;


[補充]
想一次匯出多個表格的作法!
檔名:mysql_export_csv.sql
|===========================================================================|
USE database_name ;

SELECT * INTO OUTFILE '/the/path/of/testdata1.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' FROM testdata1 WHERE 1 ;

SELECT * INTO OUTFILE '/the/path/of/testdata2.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' FROM testdata2 WHERE 1 ;

SELECT * INTO OUTFILE '/the/path/of/testdata3.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' FROM testdata3 WHERE 1 ;
|===========================================================================|
然後在OS promote下指令!
> mysql -uyouraccount -p'yourpassword' < mysql_export_csv.sql

OK!搞定~

反之匯入多個表格作法!
檔名:mysql_import_csv.sql
|===========================================================================|
USE database_name ;

TRUNCATE TABLE testdata1 ;
LOAD DATA LOCAL INFILE '/the/path/of/testdata1.csv' INTO TABLE testdata1 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' ;

TRUNCATE TABLE testdata2 ;
LOAD DATA LOCAL INFILE '/the/path/of/testdata.csv' INTO TABLE testdata2 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' ;

TRUNCATE TABLE testdata3 ;
LOAD DATA LOCAL INFILE '/the/path/of/testdata.csv' INTO TABLE testdata3 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' ;
|===========================================================================|

OS promote 指令!
> mysql -uyouraccount -p'yourpassword' < mysql_import_csv.sql

任務完成!Good luck!

沒有留言:

搜尋此網誌

本站大事記

這個部落格(網站)內容以分享LINUX和延伸出的技術文章為主!
特別是為了工作和進修需要,搜集了不少網站連結。
希望對來這裡觀文的朋友們,有提供一些有用的資訊或文章。
但這裡的文章中,也包含個人的心情扎記和隨興言談……
若是當中沒有對上你的口味,請多包涵!

原「琳娜絲與希斯寇的邂逅」,改名為「愛上琳娜絲」!

原「琳娜絲與希斯寇的邂逅」,改名為「愛上琳娜絲」!
--原序文--
就是當LINUX遇上CISCO啦!他們的結合還能作什麼事…不就是讓這個世界的網路,串…串起來啊…不然你們那能上這網站看部落格!