mysql 特殊字符

1、倒引号,比如表中有一个字段为desc,在mysql中desc是关键字,如何表明desc是字段呢?
有两种办法:desc使用倒引号引起来,或者在desc前面加上表名,如下:
mysql> select desc from student;
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc from student' at line 1
mysql> select `desc` from student;
+-------+
| desc |
+-------+
| hello |
+-------+
1 row in set

mysql> select student.desc from student;
+-------+
| desc |
+-------+
| hello |
+-------+
1 row in set
2、考虑下面的存储过程
DELIMITER ;;
CREATE PROCEDURE `qry_student`(in iName varchar(64), in iAge int)
BEGIN
select * from student where school='NUM_1' and name = iName and age>iAge;
END
;;
DELIMITER ;

如何使用动态sql语句来完成上面的功能?
注意:上面的情况,不应该使用动态sql语句,这里只是为了举例。有些复杂的业务逻辑需求,需要组成动态sql语句。
3、第一个问题,单引号当中有单引号,怎么办?
里面的单引号使用双引号,或者转义,转义有两种办法:两个单引号 '',或者 \',如下:
set vSql = concat('select * from student where school="NUM_1" ','and name =''',iName,''' and age>',iAge);
set vSql = concat('select * from student where school=''NUM_1'' ','and name =''',iName,''' and age>',iAge);
set vSql = concat('select * from student where school=\'NUM_1\' ','and name =''',iName,''' and age>',iAge);
使用双引号,拼出来的sql语句也是双引号,在mysql中,char(varchar)使用单引号和双引号都是可以的。
4、对于变量iName,也需要用单引号引起来,怎么办?
同样可以使用上面的办法,但是需要注意的是:'and name =''', 前面的单引号是最长匹配,也就是匹配最右边的单引号,匹配第三个单引号。因此,上面等价于
'and name =\'',或者 'and name ="',
5、能不能拼接成功,最简单的办法是select出来看一下。

posted on 2015-06-27 20:42  Andy Niu  阅读(4970)  评论(0编辑  收藏  举报