zoukankan      html  css  js  c++  java
  • JavaWeb学习记录(二十四)——获取插入数据后,自动生成的id值

    public Integer insertObjects(final Goods entity) {

            // 定义sql语句
            final String sql1 = "insert into goods(name,price,cid)values(?,?,?)";

            /*
             * int num = jdbcTemplate.update(sql1, new Object[] { entity.getName(),
             * entity.getPrice(), entity.getCategory() != null ?
             * entity.getCategory().getId() : null });
             */
            // 执行更新 获取自动增长id值
            // 1.max(id)获取,线程不安全

            /*
             * if(num>0){ String sql2 ="select max(id) from goods";
             *
             * return jdbcTemplate.queryForInt(sql2); }else{ return 0; }
             */

            // 2.select last_insert_id()
            /*
             * if(num>0){ //查询最后一次插入的id值 //connection 操作线程安全 String sql2
             * ="select last_insert_id()"; return jdbcTemplate.queryForInt(sql2);
             * }else{ return 0; }
             */

            
            //3.第三种方法
            // 键托管对象
            KeyHolder keyHolder = new GeneratedKeyHolder();

            // 3.方法
            int num = jdbcTemplate.update(new PreparedStatementCreator() {

                @Override
                public PreparedStatement createPreparedStatement(Connection conn)
                        throws SQLException {
                    // 执行sql语句
                    PreparedStatement ps = conn.prepareStatement(sql1,
                            Statement.RETURN_GENERATED_KEYS);
                    int index = 1;//1开始
                    ps.setString(index++, entity.getName());
                    ps.setDouble(index++, entity.getPrice());
                    if (entity.getCategory() != null) {
                        ps.setObject(index++, entity.getCategory().getId());
                    } else {
                        ps.setObject(index++, null);
                    }
                    return ps;
                }
            }, keyHolder);
            System.out.println("num==" + num);
            if (num > 0) {
                System.out.println("插入成功");
                entity.setId(keyHolder.getKey().intValue());
                return entity.getId();
            } else {
                System.out.println("插入失败");
                return 0;
            }

            //4.在使用数据库操作的框架的时候,就不涉及到这种问题
        }

  • 相关阅读:
    make ubuntu desktop beautiful
    scratch 编程第二弹
    stratch pragramming
    emacs 安装与基本设置-1
    linux相关命令
    7-12
    python strip()
    python 正则表达式 re.sub & re.subn
    python 正则表达式 re.findall &re.finditer
    python 正则表达式 re.split
  • 原文地址:https://www.cnblogs.com/ly-radiata/p/4387429.html
Copyright © 2011-2022 走看看