如果子段是递增的话就容易一点
在update后
select max(递增字段) as num from table
然后得到num的值后再commit因为如果你不commit那么一般都会锁住表的,等你commit才释放表给其他用户更新,所以select max操作得到的结果应该是你最新插入的纪录,而不是其程序插入的纪录,这就可以保证获得插入的纪录了。但是不同的数据库的纪录锁都不大相同的,最好测试一下或者看看帮助,上面的办法要求是表级锁

解决方案 »

  1.   

    如果你用的是oracle的sequence来生成自增量,那么,可以用
    select seq_name.curval num from  dual;
    来获得
    但在多用户并发访问这个sequence情况下可能会有问题
      

  2.   

    我也想知道在 DB2中如何得到 新插入记录的 ID??
    http://expert.csdn.net/Expert/topic/1295/1295287.xml?temp=.8769495
      

  3.   

    几位大哥,不好意思,我用的是ODBC->access,能说详细点吗?
      

  4.   

    请教 jimok(Jim) 
    为了得到最新的MAX,必须给table加一个锁,但是table加锁好象是数据库自己控制的,我们怎样才能给table加锁?
      

  5.   

    Retrieving auto-generated keys
    To address the common need to obtain the value of an auto-generated or auto-incremented key, the JDBC 3.0 API now makes it painless to obtain this value. To determine the value of any generated keys, simply specify in the statement's execute() method an optional flag denoting that you are interested in the generated value. Your level of interest can either be Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS. After executing the statement, the values for the generated keys are obtained by retrieving a ResultSet from a Statement's instance method, getGeneratedKeys(). The ResultSet contains a row for each generated key. The example in Listing 1 creates a new author and returns the corresponding auto-generated key. Listing 1. Retrieving an auto-generated key
    Statement stmt = conn.createStatement();
    // Obtain the generated key that results from the query.
    stmt.executeUpdate("INSERT INTO authors " +
                       "(first_name, last_name) " +
                       "VALUES ('George', 'Orwell')",
                       Statement.RETURN_GENERATED_KEYS);
    ResultSet rs = stmt.getGeneratedKeys();
    if ( rs.next() ) {
        // Retrieve the auto generated key(s).
        int key = rs.getInt(1);
      

  6.   

    masterz(MS MVP)兄说得好,可惜JDBC3.0是刚刚出来的,目前市面上的绝大部分JDBC驱动程序恐怕还不支持,能够支持到JDBC2.0已经不错了.
    如果不是3.0的,恐怕只能用事务做了.
      

  7.   

    学了不少东西,我还是用了最土的办法,从头到尾跑了一边
    同时我搞明白了另一个问题
    我在int n=ResultSet.getInt(1);设了一个断点,设了一个watch:ResultSet.getInt(1)结果对n复值时就no data found了
    为什么ResultSet对每个字段只能get一次?还有ResultSet.last();我理解是到最后一记录,错误说指针是单向的?
      

  8.   

    根据我的情况,我觉得还是jimok(Jim)的方法最好多谢大家,分不多,来者有份。
      

  9.   

    另外,access是否支持Scrollable ResultSet?
      

  10.   

    con.setAutoCommit(false);
    这样设置后就不会立刻更新数据库要commit才更新数据库,不commit之前应该就会锁表吧,access应该是表级锁的
      

  11.   

    scrollable resultset要看看jdbc的驱动支不支持
    Statement state = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = state.executeQuery("select * from table1");
    这样就是回滚了如果想知道是不是能够回滚可以测试一下,或者看看设置回滚是否成功
    System.out.println(ResultSet.TYPE_SCROLL_INSENSITIVE);
    System.out.println(state.getResultSetType());
    看看上面两个值是否相同