由于工作需要,經(jīng)常需要將mysql數(shù)據(jù)庫(kù)中的數(shù)據(jù)導(dǎo)出到excel表格,或者需要將excel表格數(shù)據(jù)導(dǎo)入到mysql數(shù)據(jù)庫(kù),我的方法是先將它們都轉(zhuǎn)換成一種中間數(shù)據(jù)格式csv(execl數(shù)據(jù)可以直接導(dǎo)出為csv格式,csv格式也可以直接用excel打開)。下面介紹一下操作步驟:
成都創(chuàng)新互聯(lián)公司成立于2013年,先為綠園等服務(wù)建站,綠園等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為綠園企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
csv導(dǎo)入mysql
load data infile 'C:\\Users\\UserName\\Desktop\\test.csv'
into table `table`
fields terminated by ',' optionally enclosed by '"' escaped by '"'
lines terminated by '\n';
mysql導(dǎo)入csv
select * from `table`
load data infile 'C:\\Users\\UserName\\Desktop\\test.csv'
fields terminated by ',' optionally enclosed by '"' escaped by '"'
lines terminated by '\n';
如果亂碼,可用相關(guān)編輯器打開.csv文件,另存為utf-8的csv
mysql導(dǎo)出數(shù)據(jù)庫(kù)到csv文件的方法:
1、通過mysql客戶端shell連接到服務(wù)器,選擇使用的數(shù)據(jù)庫(kù),輸入sql代碼:
select * from test_info
into outfile '/tmp/test.csv'
fields terminated by ',' optionally enclosed by '"' escaped by '"'
lines terminated by '\r\n';
里面最關(guān)鍵的部分就是格式參數(shù)
這個(gè)參數(shù)是根據(jù)RFC4180文檔設(shè)置的,該文檔全稱Common Format and MIME Type for Comma-Separated Values (CSV) Files,其中詳細(xì)描述了CSV格式,其要點(diǎn)包括:
(1)字段之間以逗號(hào)分隔,數(shù)據(jù)行之間以\r\n分隔;
(2)字符串以半角雙引號(hào)包圍,字符串本身的雙引號(hào)用兩個(gè)雙引號(hào)表示。
通過執(zhí)行上述代碼,便可以將需要的數(shù)據(jù)以csv格式導(dǎo)出到執(zhí)行的文件中。
2、另外,MySQL中導(dǎo)入CSV格式數(shù)據(jù)的sql代碼如下:
load data infile '/tmp/test.csv'
into table test_info
fields terminated by ',' optionally enclosed by '"' escaped by '"'
lines terminated by '\r\n';
1.MySQL導(dǎo)出本地?cái)?shù)據(jù)庫(kù)數(shù)據(jù)到本地文件
Sql代碼
代碼如下 復(fù)制代碼
load data infile '/tmp/test.csv'
into table test_info
fields terminated by ',' optionally enclosed by '"' escaped by '"'
lines terminated by 'rn';
load data infile '/tmp/test.csv'
into table test_info
fields terminated by ',' optionally enclosed by '"' escaped by '
"'
lines terminated by 'rn'; 里面最關(guān)鍵的部分就是格式參數(shù)
2.MySQL導(dǎo)出遠(yuǎn)程數(shù)據(jù)庫(kù)數(shù)據(jù)到本地文件
代碼如下 復(fù)制代碼
mysql -A service_db -h your_host -utest -ptest -ss -e "SELECT * from t_apps limit 300;" | sed 's/t/","/g;s/^/"/;s/$/"/;s/n//g' apps.csv
(sed部分可略,尤其是處理包含漢字的數(shù)據(jù)時(shí))
3. mysqldump導(dǎo)出csv格式的數(shù)據(jù)文件
代碼如下 復(fù)制代碼
# 使用方法如下
mysqldump -uroot -ppassword -t -T/root testdb --fields-enclosed-by=" --fields-terminated-by=,
例
mysqldump -h your_host -utest -ptest -w "id300" service_db t_apps tt.sql
導(dǎo)出后格式如下:
代碼如下 復(fù)制代碼
"1","m11401","2013-06-22 23:00:01"
"2","m11402","2013-06-22 23:00:02"
"3","m11403","2013-06-22 23:00:03"
1、首先創(chuàng)建要插入100萬(wàn)數(shù)據(jù)的表格,隨機(jī)產(chǎn)生數(shù)字。
2、其次創(chuàng)建存儲(chǔ)過程,并向表中插入數(shù)據(jù),調(diào)用存儲(chǔ)過程進(jìn)行插入數(shù)據(jù),插入300萬(wàn)條數(shù)據(jù),且分幾次插入。
3、最后導(dǎo)出數(shù)據(jù)到csv,使用函數(shù)selectxxxintooutfile,其中outfile后面的路徑可以是Windows或macOS或者Linux。