Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4161219
  • 博文数量: 240
  • 博客积分: 11504
  • 博客等级: 上将
  • 技术积分: 4277
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-28 14:24
文章分类

全部博文(240)

分类: Mysql/postgreSQL

2007-12-06 10:52:18

1、今天写的一个存储过程,发现MYSQL的特殊字符和动态处理语句结合起来要转义好几次 。
贴出我的问题以及解决方法。

表结构:

/*DDL Information For - test.cs_test*/
--------------------------------------

Table    Create Table                            
-------  -----------------------------------------
cs_test  CREATE TABLE `cs_test` (                
           `id` int(11) NOT NULL auto_increment, 
           `name` varchar(64) default NULL,      
           PRIMARY KEY  (`id`)                   
         ) ENGINE=InnoDB DEFAULT CHARSET=utf8    

存储过程1:(静态,也就是不用预处理的部分。)


DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`sp_normal_test`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_normal_test`(IN f_id int,
 IN f_name varchar(64),OUT f_error_code boolean)
BEGIN
  -- Determinate whether update is successful or failed.
  declare cnt int default 0;
  -- Update to new record.
  update cs_test
  set `name` = f_name
  where id = f_id;
  -- Get the affective rows.
  set cnt = row_count();
  -- Get the last record.
  if cnt > 0 then
    set f_error_code = TRUE;
   end if;
END$$

DELIMITER ;


存储过程2:(用预处理部分。)


DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`sp_dynamic_test`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_dynamic_test`(IN f_id int,
 IN f_name varchar(64),OUT f_error_code boolean)
BEGIN
  -- Determinate whether update is successful or failed.
  declare cnt int default 0;
  -- Update to new record.
  set @stmt = concat('update cs_test set `name` =''',f_name,'''');
  set f_error_code = FALSE;
  if f_id != 0 then
    set @stmt = concat(@stmt, ' where id = ',f_id);
  end if;
  prepare s1 from @stmt;
  execute s1;
  -- Must be above of the deallocate statement.
  set cnt = row_count();
  deallocate prepare s1;
  -- Get the last record.
  if cnt > 0 then
    set f_error_code = TRUE;
   end if;
END$$

DELIMITER ;


表之前的数据:

select * from cs_test;


结果:

uery result(9 records)

id name
1 csdn1
2 colorful1
3 bbs1
4 cu1
5 cu2
6 woshiduide
7 woshicuode
8 I'm wrong
9 I'm right

调用存储过程1:
如果你要把ID为6的记录对应的NAME字段更新为'woshiduide\n\n\n\n\n'的话,只能这样调用:

call sp_normal_test(6,'woshiduide\\n\\n\\n\\n\\n',@e);
select @e;

select * from cs_test where id = 6;


query result(1 records)

@e
1

query result(1 records)

id name
6 woshiduide\n\n\n\n\n


这里\n中的反斜杠是要转义的,要不然就会出现非自己想要的结果。
调用存储过程2:

call sp_dynamic_test(6,'woshiduide\\n\\n\\n\\n\\n',@e);
select @e;
select * from cs_test where id = 6;


结果:

query result(1 records)

@e
1

query result(1 records)

id name
6 woshiduide

这样的结果不是我们想要的。
正确调用如下:

call sp_dynamic_test(6,'woshiduide\\\\n\\\\n\\\\n\\\\n\\\\n',@e);
select @e;
select * from cs_test where id = 6;


结果:

query result(1 records)

@e
1

query result(1 records)

id name
6 woshiduide\n\n\n\n\n


这个要进行两次转义。具体原因等一下再说。因为我现在还不知道怎么表述才是最好的。
阅读(6231) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~