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出來看一下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM