现在遇到一个问题,MySQL数据库中有个images字段,用于存取文章中所有图片地址,有些地址是基于服务器的绝对路径,例如/watercms/upload/image/20160204/1454573950573007716.jpg,/watercms/upload/image/20160204/1454573944458029036.jpg,如果是App访问的话,这些图片就读取不出来了,因此通过存储过程来把字段中的图片路径,修改为带网络地址的路径。
思路:先将images字段,通过间隔符split成单个的图片地址,然后判断当前地址是否以http开头,如果不是,则加上http,然后把单个的图片地址再拼接起来,update到数据库中。
DROP FUNCTION IF EXISTS func_get_split_string_total;CREATE FUNCTION func_get_split_string_total(f_string TEXT,f_delimiter varchar(5)) RETURNS int(11)BEGIN RETURN 1 + (length(f_string) - length(replace(f_string,f_delimiter,'')));END
定义方法,计算字符串通过,分隔符功能分隔成几段
DROP FUNCTION IF EXISTS func_split_str;CREATE FUNCTION func_split_str( x VARCHAR(5000), delim VARCHAR(12), pos INT)RETURNS VARCHAR(500)BEGINRETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1), delim, '');END
定义方法取得通过分隔符分割成段的第几段字符。
CREATE PROCEDURE `pro_update_knowledge_images`()BEGIN DECLARE done INT DEFAULT FALSE; DECLARE kid INT; DECLARE images VARCHAR(5000); DECLARE new_img VARCHAR(200); DECLARE new_imgs VARCHAR(5000); DECLARE image_count INT; DECLARE i_index INT; DECLARE k_images_cursor CURSOR FOR SELECT k.id,k.images FROM ww_article_knowledge k WHERE k.`status` = 1 AND k.images IS NOT NULL AND k.images!=''; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN k_images_cursor; read_loop:LOOP FETCH k_images_cursor INTO kid,images; IF done THEN LEAVE read_loop; END IF; SET image_count = func_get_split_string_total(images,','); SET i_index = 1; SET new_imgs = ''; WHILE i_index<=image_count DO SET new_img = func_split_str(images,',',i_index); IF new_img NOT LIKE 'http%' THEN SET new_img = CONCAT('http://uhome.haier.net:8280',new_img); END IF; IF i_index > 1 THEN SET new_imgs = CONCAT(new_imgs,',',new_img); ELSE SET new_imgs = new_img; END IF; SET i_index = i_index + 1; END WHILE; UPDATE ww_article_knowledge SET images=new_imgs WHERE id=kid; COMMIT; END LOOP; CLOSE k_images_cursor;END
利用游标,对表的images字段进行处理。