【存儲過程】從數據庫中讀取數據保存到文件中

         因爲初期規劃很差,項目管理的action都存入到數據庫中了,而實際上應該以配置文件的形式保存的,因此如今想改過來。一條條複製是不可能的,幾百條記錄,能夠用java編寫個小程序或者其餘語言編寫個腳原本實現,都很簡單,但由於這兩天在學存儲過程,因此就試着寫一個了(數據庫的過程、函數和觸發器等真的很好玩啊!)。 
        其實這個過程只有兩個要點:
        ①如何從數據庫中讀取出全部action並且沒有重複(由於以前不少失誤操做,寫入不少重複的記錄);
        ②如何把讀出來的集合轉換成properties的格式並寫入文件。
        
        ①的查詢語句:
        select C_ACTION,B_POWER from p_link where I_ID in
java

        (select max(I_ID) from p_link group by C_ACTION); sql


        ②循環處理讀出來的集合,拼裝成一個大串,一次性寫入文件:(使用光標來遍歷集合)
數據庫

        repeat小程序

fetch c_cursor into tmp_action,tmp_power;函數

if not i_done thenfetch

set c_content = concat(c_content, tmp_action, '=', tmp_power, char(13));spa

end if;code

until i_done end repeat;ci

        最終可獲得一行行結構爲 XXX=XXX 鍵值對。項目管理

詳細代碼以下:

drop procedure if exists get_all_links;
delimiter $$
create procedure get_all_links()
	begin
	
	declare c_content text;
	declare i_done int default 0; 
	declare tmp_action varchar(100);
	declare tmp_power tinyint;
	
	declare c_cursor cursor for
		select C_ACTION,B_POWER from p_link where I_ID in
		(select max(I_ID) from p_link group by C_ACTION);
	declare continue handler for sqlstate '02000' set i_done = 1;
	
	open c_cursor;
	set c_content = '';
	repeat
		fetch c_cursor into tmp_action,tmp_power;
		if not i_done then
			set c_content = concat(c_content, tmp_action, '=', tmp_power, char(13));
		end if;
	until i_done end repeat;
	close c_cursor;
	
	select c_content into outfile 'D:\\action.properties';
	
	end
$$
delimiter ;
call get_all_links();
drop procedure get_all_links;
相關文章
相關標籤/搜索