mysql導出csv一種簡單方法


可以寫py腳本導出,但是感覺沒有直接寫sql靈活,於是寫了一個函數,直接傳一段sql,導出csv到指定目錄:

(1)nas上掛載一個目錄:

mount -t xfs -o defaults,rw,noatime,nodiratime,nobarrier,noikeep,attr2,largeio,inode64,swalloc,allocsize=1 172.18.x.x:/volume1/DBBackup /mnt/csv

(2)my.cnf添加配置(需要重啟實例)

#啟用LOAD DATA功能
local_infile=1
secure_file_priv=/mnt/csv

mysql8.0說最好不要開啟 secure_file_priv 這個,因為不太安全,這個還是看管理情況了,我開啟了,然后nas映射目錄。然后直接數據庫導出導指定目錄

(3)寫sql函數:

delimiter $$
use `report`$$
drop procedure if exists `proc_exp_select_tab`$$
create definer=`report`@`%` procedure `proc_exp_select_tab`(in i_sql varchar(2000),tab varchar(40))
begin
 declare tb_name varchar(40);
    set @tab_name=concat(tab,date_format(now(),'%h%i%s'),'.csv');
    set tb_name=@tab_name;
    set @exe_sql=concat('with t as(',i_sql,')','select * into outfile \'/mnt/csv/',tb_name,'''',' character set gbk fields terminated by \',\' optionally enclosed by \'"\' lines terminated by \'\\n\' from t');
   -- write the resultset to the file
   prepare stmt from @exe_sql;
   execute stmt;
   deallocate prepare stmt;
   select concat('請訪問url : ','http://xxxxxxx',' : ',tb_name) as '文件信息';
end$$
delimiter ;age:

ege:

call proc_exp_select_tab('select xxxxx','test')

然后數據就存到操作系統 /mnt/csv/ 這個目錄,nas上在配置一個前端nginx訪問的的地址,直接web就可以下載剛才的導出的sql語句了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM