开发者

Is Java.sql's getRow() thread safe?

Lets say I have a large number of threads inserting into a mysql database using Java.sql. After i perform an insert i would like to know the primary key of the record i just inserted. I could use getRow() on the ResultSet returned by the insert query. However, is this thread safe? Or should I fire off another select statemen开发者_开发问答t to find the primary key of the record I just inserted?


ResultSet does not advertise on the javadoc as being thread safe, so assume it is NOT. If you have 10 threads inserting, and somehow they get the SAME result set.. something weird will happen (or at least not guarantee to be right).

However, if you have 10 threads each doing their OWN inserting, and each one has it's own ResultSet .. you are fine. Remember, thread safety often has to do with sharing of the same OBJECT, not just the same class. ArrayList is NOT thread safe, but if you have 10 different threads with 10 different ArrayList's, you are fine. Same here with ResultSet.


I don't think getRow() should be correct. getId() would be my choice, because the row ID may not be the same as the generated primary key.

I don't believe that any implementation in java.sql is thread-safe; Connection certainly is not.

Be sure to make your INSERT in a transaction context.

You need to pay attention to your isolation level. Check the javadocs for java.sql.Connection if you don't know what that means.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜