Java acquire the newly inserted data in the database Id (primary key, automatic growth)

public int insert(String cName, String ebrand, String cGender) {
		String sql = "insert into Cloth (cname,ebrand,cgender) values(?,?,?) ";
		Connection conn = DruidUtil.getConn();
		PreparedStatement prep = null;
		ResultSet rs = null ;
		try {
			prep = conn.prepareStatement(sql,
                    PreparedStatement.RETURN_GENERATED_KEYS);
			prep.setString(1, cName);
			prep.setString(2, ebrand);
			prep.setString(3, cGender);
            prep.executeUpdate();
            rs = prep.getGeneratedKeys();
            if (rs.next()) {
            //获取插入数据的Id(主键,自增长)
            int cId = rs.getInt(1) ;
            // 返回这个Id
                return cId ;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
        	 DruidUtil.close(conn, prep, rs);
        }
		return -1;
     
    }

  This embodiment is used in the database mysql, getGeneratedKeys to use () when using the return value to obtain jdbc rs 

    Where id primary key in the database, since the growth of type int

        rs.getInt (1) acquired from the specific numerical id growth  

    Id as the return value.

= conn.prepareStatement Prep (SQL, 
                    PreparedStatement.RETURN_GENERATED_KEYS); 
			prep.setString (. 1, cName); 
			prep.setString (2, ebrand); 
			prep.setString (. 3, cGender); 
            prep.executeUpdate (); 
            RS = Prep. getGeneratedKeys to (); 
            IF (rs.next ()) { 
            // Get Id insert data (primary key, since the increase) 
            int rs.getInt CID = (. 1); 
            // returns the Id 
                return CID; 
            }

 

Guess you like

Origin www.cnblogs.com/ZT-Song/p/11361076.html