Java从MySQL查询时如何将INT类型ID转为字符串?代码问题与解决
问题解决:通过ID查询数据库中纸杯蛋糕配料名称
我正在开发一个简单的纸杯蛋糕网店Web应用,用户从下拉菜单选择的纸杯蛋糕三个属性(top、bottom、quantity)会以数字形式存储在sessionScope的ArrayList中(例如巧克力对应1,香草对应2)。原本想通过topId整数从MySQL数据库查询对应的配料名称,但最初的代码无法返回正确的字符串结果。
初始问题代码
public static Top getTopById(int topId) { readFromArrayPutInSQL(); String sql = "INSERT INTO cupcaketopping (toppingType, toppingPrice) VALUES (?, ?)"; try { ConnectionPool connectionPool = new ConnectionPool(); String query = "SELECT toppingType FROM cupcaketopping"; Statement statement = connectionPool.getConnection().createStatement(); ResultSet rs = statement.executeQuery(query); rs.getString(topId); } catch (SQLException e) { throw new RuntimeException(e); } return topId; //Here is the problem - I GUESS? }
初始代码的问题点
- 存在冗余的INSERT语句,未被实际调用
- 查询语句未添加
WHERE条件过滤指定topId,会返回所有配料类型,而非目标ID对应的记录 - 调用
rs.getString(topId)时,既没有移动结果集指针(rs.next()),且参数误用了topId值(该方法参数应为列索引或列名) - 方法返回类型为
Top,但最终返回了int类型的topId,类型完全不匹配
修改后可正常运行的代码
public static Top getTopById(int topId) { readFromArrayPutInSQL(); String query = "SELECT toppingType FROM cupcaketopping WHERE toppingID = "+topId+""; try { ConnectionPool connectionPool = new ConnectionPool(); PreparedStatement preparedStatement = connectionPool.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(query); rs.next(); return new Top(rs.getString(1)); //connectionPool.close(); //NOTE! Won't run, IntelliJ is asking me to delete! } catch (SQLException e) { throw new RuntimeException(e); } }
修改说明
- 修正查询语句,添加
WHERE toppingID = ?(注:直接拼接topId存在SQL注入风险,更安全的做法是使用preparedStatement.setInt(1, topId),并将SQL改为SELECT toppingType FROM cupcaketopping WHERE toppingID = ?) - 使用
PreparedStatement替代Statement,提升代码安全性和可维护性 - 添加
rs.next()移动结果集指针到第一条记录,确保能正确获取查询结果 - 返回正确的
Top实例,用查询到的toppingType字符串初始化 - 关于
connectionPool.close()无法执行:因为该语句位于return之后,代码执行到return就会结束方法,后续代码永远不会被执行,所以IDE提示删除。此外,连接池的连接通常需要在finally块中归还,而非直接调用close,具体需遵循连接池的使用规范
内容的提问来源于stack exchange,提问作者Narj
相关产品推荐
相关产品推荐

