怎么动态获取数据库表中自动递增id的值

描述:现在有两张表,emp员工表和calling行业表 两者是多对多的关系,一个员工可以有多种行业,而一个行业内也有很多员工所以需要建立一个中间表id_calling。如下图:

前段数据页面在这不演示了,

提交表单后,后台服务器获取各种属性,传递到数据处理层,也就是数据库的插入操作。

代码执行:

    //数据传递

    public void getEmpList(String name, String phone, String cid, String b_name, String email,String[] calling) {

    //进行数据库操作

        Connection connection=null;

        PreparedStatement pst=null;  

        ResultSet rs=null;

    //把传递的cid也就是公司性质的代号转为Integer类型

        Integer cidd=Integer.parseInt(cid);

    //第一个sql语句先插入员工表数据,插入传递的参数,使用占位符

        String sql="insert into emp set name=?,phone=?,cid=?,b_name=?,email=?;";

    //第二个sql语句当插入完成后获取的最后一个自动递增的id的值 注意:select last_insert_id()这条sql语句必须跟执行插入操作的语句是同一个数据连接,否则无效。

        String sql2="select last_insert_id();";
        try {
            //连接JDBC工具类,执行加载驱动,连接数据库的操作
            connection=JDBCUtils.connection();

            pst=connection.prepareStatement(sql);

            //设置第一个占位符的值

            pst.setString(1, name);
            pst.setString(2, phone);
            pst.setInt(3, cidd);
            pst.setString(4, b_name);

            pst.setString(5, email);

            //执行sql更新语句

            pst.executeUpdate();

              //执行sql2的查询语句,获取结果集

            rs=pst.executeQuery(sql2);

            Integer id=null;

              //打印结果集

            if(rs.next()) {

                //获取di

                id=rs.getInt(1);            
            }
           //调用添加表的方法,把emp,calling表的id,calling  穿递过去执行插入操作
            addCalling(id,calling);    
        } catch (Exception e) {
            
        }finally {
                JDBCUtils.close(null, pst, connection);
        }
        
    }

//插入中间表  

public void addCalling(Integer id,String[] calling) {

//使用DBUtils 工具类进行数据库的操作

        QueryRunner runner =new QueryRunner();

        try {

//遍历传递的行业数组,执行插入操作  因为行业是复选框,可以多选,传递的是一个行业数组

            for(int i=0;i<calling.length;i++) {
                runner.update(JDBCUtils.connection(), "insert into id_calling set id=?,caid=?",id,calling[i]);    
            }
            
        } catch (SQLException e) {
            
            e.printStackTrace();
        }    

    }

//添加成功












猜你喜欢

转载自blog.csdn.net/yuanboqi/article/details/80658081