在水一万 发表于 2018-9-29 10:26:32

关于MYSQL 字符转义问题总结

1、今天写的一个存储过程,发现MYSQL的特殊字符和动态处理语句结合起来要转义好几次 。  贴出我的问题以及解决方法。
  表结构:
  /*DDL Information For - test.cs_test*/
  --------------------------------------
  Table    Create Table
  ------------------------------------------------
  cs_testCREATE 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>  -- 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>  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)
idname1csdn12colorful13bbs14cu15cu26woshiduide7woshicuode8I'm wrong9I'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>
query result(1 records)
@e1query result(1 records)
idname6woshiduide\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>  结果:
query result(1 records)
@e1query result(1 records)
idname6woshiduide  这样的结果不是我们想要的。
  正确调用如下:
call sp_dynamic_test(6,'woshiduide\\\\n\\\\n\\\\n\\\\n\\\\n',@e);  select @e;

  select * from cs_test where>  结果:
query result(1 records)
@e1query result(1 records)
idname6woshiduide\n\n\n\n\n  这个要进行两次转义。具体原因等一下再说。因为我现在还不知道怎么表述才是最好的。

页: [1]
查看完整版本: 关于MYSQL 字符转义问题总结