m-y m-y - 1 month ago 14
C# Question

C#: How do I get the ID number of the last row inserted using Informix

I am using the Informix.NET driver (C#) to insert a row into a database table. This works fine, except I have no idea how to get the ID of the last inserted row:

Insert Command:

//Sample Query: "INSERT INTO names (id, name) values (0, 'John Smith');"
public static void Insert(String query)
{
try
{
using (IFX::IfxConnection connection = ConnectionManager.GetConnection())
{
connection.Open();

using (IFX::IfxCommand command = new IFX::IfxCommand(query, connection))
command.ExecuteNonQuery();

if (connection != null) connection.Close();
}
}
catch (IFX::IfxException)
{
throw;
}
catch (Exception)
{
throw;
}
}


If I change the query so that it includes: "SELECT DBINFO ('sqlca.sqlerrd1') FROM systables WHERE tabid = 1;" I get errors (this line works using unix dbaccess) I get errors.

I've also tried to change things such as using
IFX::IfxReader reader = command.ExecuteReader()
to try to get the results and read those results, however I get errors. ("ERROR [HY000] [Informix .NET provider][Informix]Cannot use a select or any of the database statements in a multi-query prepare."). I've also tried to precede this with
command.Prepare();
, but that does nothing. I'm really not sure how to do an insert and get the ID through C# Informix.NET Client SDK.

=========

Oh, and I know I can run the two statements separately, which will work, except I'm worried that another insert will be executed in between the first and getting the ID number, which would result in errors.

Answer

Granted I've never used this framework before, but I did needed like this in a different framework I worked with so what I ended up doing was doing a completely separate query to get the new element's ID.

My code was in PHP but in pseudocode it looked like:

Insert(String query)
{
   Execute the Sql Query: query
   result = Execute the Sql Query: "SELECT last_insert_id"
   return the first element of result
}

EDIT: I didn't notice your edit, and that wasn't an issue for me because it was PHP so it was single-threaded and so it was impossible for another statement to execute in the time between the two queries. However, if you add a lock to inserts you can force that both queries happen as a transaction. Also with a bit of RegEx you could probably construct a Select statement that uses the information in the Insert statement.