tags:

views:

92

answers:

1

I have derived my own component from TAdoQuery in Delphi. I have overridden the DoAfterPost procedure; and in this code I create another query for the purpose of fetching the primary key associated with an inserted record (i.e. SELECT @@IDENTITY for SqlServer, SELECT LAST_INSERT_ID() for MySql, etc).

In the past I always used TAdoConnection for database connectivity. And in the "subquery" call made within DoAfterPost there was no problem because it was the SAME Session (these queries to retrieve last inserted primary keys assume a persistent database connection).

I recently made an option where instead of using a TAdoConnection connection, I am instead setting the ConnectionString property (for multi-thrading purposes). But this creates a problem because the spawned subquery does not use the same session as the main query. Hence it does not return the primary key value.

My question is, does TAdoQuery have any Connection property if the ConnectionString is used? I could then daisychain this connection/session to my subquery. Or is the only way to accomplish this via a TAdoConnection?

+2  A: 

@M Schenkel, when you set the ConnectionString property of the TADOQuery component, the TAdoQuery create a new connection to the database with a new session id.

the @@IDENTITY SQL Server function return the last-inserted identity value in the current session , because that you need to use the same Connection (and session) for the insert statement and the query SELECT @@IDENTITY.

As workaround in sql server you can use the IDENT_CURRENT function wich is not limited to an session.

In MySql the LAST_INSERT_ID() function also works on a perconnection. therefore the behavior is similar to the function @@IDENTITY.

In short, the best option you have is to use an unique TAdoConnection object.

RRUZ
Thank you. Very helpful. So it seems there is NO WAY to retain the session object. I will follow up and apply the unique TAdoConnection method.
M Schenkel