简体   繁体   English

自动提交设置为false时,select是否返回最后插入的行?

[英]Does select return last inserted row while autocommit set false?

Say I have a table named users and a column named username with the format user1, user2 .. 假设我有一个名为users的表和一个名为username的列,其格式为user1,user2 ..

I want to insert users into this table in a loop and value of every entry depends on the one's before. 我想将用户循环插入此表中,每个条目的值取决于以前的值。 Value of the new entry is generated by the alphabetically greatest entry in the table, namely users . 新条目的值由表中按字母顺序排列的最大条目(即users)生成

Since it's possible in JDBC API to getGeneratedKeys after an insert while AutoCommit set to false; 因为在JDBC API中有可能在AutoCommit设置为false时插入后获得getGeneratedKeys

In a situation like given below: 在如下所示的情况下:

connection.setAutoCommit(false);
while(someCondition)
{
    ResultSet rs = connection.createStatement("select max(username) from users").executeQuery();
    if(rs.next())
    { 
        name= rs.getString("username"); //returns user1
    }
    String newName = generateNewName(name); // simply makes user1 -> user2

    connection.createStatement("insert into users (name,...) values ("+newName+",...)").executeUpdate(); ///and inserts..
}

does the select query return the last inserted value or it returns the max column in the table before I start the loop ? 选择查询返回的是最后插入的值,还是返回开始循环之前表中的max列?

First, to make sure you see all changes on the database immediately prefer TransactionIsolation of READ_UNCOMMITED over using auto commit. 首先,要确保您看到数据库上的所有更改,都比使用自动提交更喜欢READ_UNCOMMITED的TransactionIsolation。 Alternatively using auto commit everywhere would do the job, too. 另外,在任何地方使用自动提交也可以完成这项工作。

Once you made sure you see every db change immediately, the database will send you the maximum user from some time during the selects execution. 一旦确定您立即看到每个数据库更改,数据库就会执行选择期间的某个时间向您发送最大用户数。 But once you actually receive the result there might be additional users created by others threads. 但是,一旦实际收到结果,其他线程可能会创建其他用户。 Thus this will only work for a single thread working and most likely that doesn't make any sense nowadays. 因此,这仅适用于单线程工作,并且很可能在当今没有任何意义。

TL:DR No, don't do it! TL:DR不,不要这样做!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM