比如说我注册一个用户,注册成功后,应该随即取到这个用户的ID ,再根据这个用户的ID取到整个对象
1、注册成功后用用户名做为where条件,但我这里允许用户名有一致的,不行
2、insert into(...)values(...) ;select @@identity;这样也不行,执行executeUpdate()返回的是受影响的行数,不是第一行第一列的值,知道.net里是可以取到的
3、单独执行select @@identity ,也不行可能取到别人注册的用户。。
其它暂时想不到了     如何才能取到呢~?

解决方案 »

  1.   

    有点听不懂楼主的意思。一般INSERT一条记录返回值就是主键。
      

  2.   

    可能是我理解能力有限,似懂非懂!!!
    用的是mysql数据库?设置ResultSet。TYPE_SCROLL_INSENSITIVE?先执行insert,然后就select?
    如果是这样的话,问题就是是INSENSITIVE,不及时更新,就是如果数据库里的数据修改过,并不在ResultSet中反应出来。所以你select不出来。
      

  3.   

    把插入SQL改成存储过程返回来吧
      

  4.   

    用的是sql server 2005数据库的,在程序中用这段代码实现 增加和查询。
    String sql = "insert into PetInfo (pet_name,pet_sex,pet_strength,pet_cute,pet_love,pet_intro,pet_owner_name,pet_owner_email,pet_password,pet_pic,pet_type) values (1,1,1,1,1,1,1,1,1,1,1);  select @@identity as rows";执行结果是可以查出的,并且返回最一条数据的ID. 
    .net 中是可以做的,他返回的是第一行第一列的数据 ,这里由于JAVA里没有跟它一样的方法,所以不能实现
      

  5.   

    /**
     * 添加宠物信息
     */
    public int insertPet(PetInfo p) {
    int id = 0;
    Connection connection = null;
    PreparedStatement pStatement = null;
    ResultSet rSet = null; String sql = " insert into PetInfo (pet_name,pet_sex,pet_strength,pet_cute,pet_love,pet_intro,pet_owner_name,pet_owner_email,pet_password,pet_pic,pet_type) values (?,?,?,?,?,?,?,?,?,?,?) ;  "; connection = ConnectionManager.getConnection();
    try {
    int index = 1;
    pStatement = connection.prepareStatement(sql);
    pStatement.setString(index++, p.getPet_name());
    pStatement.setString(index++, p.getPet_sex());
    pStatement.setString(index++, p.getPet_strength() + "");
    pStatement.setString(index++, p.getPet_cute() + "");
    pStatement.setString(index++, p.getPet_love() + "");
    pStatement.setString(index++, p.getPet_intro());
    pStatement.setString(index++, p.getPet_owner_name());
    pStatement.setString(index++, p.getPet_owner_email());
    pStatement.setString(index++, p.getPet_password());
    pStatement.setString(index++, p.getPet_pic());
    pStatement.setString(index++, p.getPet_type() + ""); pStatement.executeUpdate(); sql = "select @@identity as id "; pStatement = connection.prepareStatement(sql);
    rSet = pStatement.executeQuery(); if (rSet.next()) {
    id = rSet.getInt("id");
    } /* 添加参数 */
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally {
    try {
    rSet.close();
    pStatement.close();
    connection.close();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } } return id;
    }
      

  6.   

    楼主,你把Sql语句改成String sql=insert into(...)values(...) ;select @@identity;把下面的这几句去掉,
    pStatement.executeUpdate(); sql = "select @@identity as id "; 
    肯定可以,我做过这道题!!
      

  7.   

    忘了告诉你,你把
    if (rSet.next()) { 
    id = rSet.getInt("id"); 
    } 改成;
    if (rSet.next()) { 
    id = rSet.getInt(1);