在xml文件中编写SQL语句的坑:因为错误使用${}了插入语句导致向数据库中插入数据失败,
insert into payment(serial) values(${serial});
正确的SQL语句应为
insert into payment(serial) values(#{serial});
原因是:
#{}传参会把serial字段值当作字符串,这样的做法比${}传参安全性高,可以防止恶意SQL注入
${}传参只会正常解析,没有加上字符串,控制台打印的SQL语句为### SQL: insert into payment(serial) values(jerry002);
就可以验证这点
报错如下:
2022-07-11 20:20:53.745 ERROR 17464 --- [nio-8001-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'jerry002' in 'field list' ### The error may involve com.atguigu.springcloud.dao.PaymentDao.create-Inline ### The error occurred while setting parameters ### SQL: insert into payment(serial) values(jerry002); ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'jerry002' in 'field list' ; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'jerry002' in 'field list'] with root cause
修改为#{}传参后: