【存储过程】从数据库中读取数据保存到文件中

         因为初期规划很差,项目管理的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;