JAVA——prepareStatement中SQL语句中占位符(?)替换表名和字段名

基本概念

PreparedStatement:Statement的改良版,具有预编译功能,方便使用,运行速度快。

问题描述

1.根据测试占位符?不能用于表名

String strSql="SELECT * FROM ?";
try(PreparedStatement ps=conn.prepareStatement(strSql)) {
    ps.setObject(1,"person");

会提示SQL语法错误

Exception in thread "main" java.lang.RuntimeException: java.sql.SQLSyntaxErrorException: 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 ''person''

2.占位符?用于其它变量名时,执行正常

String strSql="SELECT * FROM person WHERE name =?";
try(PreparedStatement ps=conn.prepareStatement(strSql)) {
    ps.setObject(1,"张三");
    ResultSet rs=ps.executeQuery();


参考文章

https://blog.csdn.net/L_BestCoder/article/details/70943649

https://blog.csdn.net/weixin_42509123/article/details/89842209

https://blog.csdn.net/u011510825/article/details/81807253

https://www.cnblogs.com/gklsy/archive/2012/01/10/2317934.html

发布了1346 篇原创文章 · 获赞 226 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/weixin_43272781/article/details/103933987