随笔 - 576  文章 - 0  评论 - 62  阅读 - 219万

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   Andy Niu  阅读(4993)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示