title: Firebird/IBPP: How to retrieve ID generated by a database autoincrement?
body: <p>I configured my firebird database to autoincrement the primary key of the table.</p>
  
  <pre><code>CREATE GENERATOR GEN_CHANNEL_PARAMETER_SET_ID;
  SET GENERATOR GEN_CHANNEL_PARAMETER_SET_ID TO 0;
  
  CREATE TRIGGER CHANNEL_PARAMETER_SETS_BI FOR CHANNEL_PARAMETER_SETS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  BEGIN
      if (NEW.CHANNEL_PARAMETER_SET_ID is NULL) then NEW.CHANNEL_PARAMETER_SET_ID = GEN_ID(GEN_CHANNEL_PARAMETER_SET_ID, 1);
  END
  </code></pre>
  
  <p>Now, in my C++ program using IBPP I have the following problem:</p>
  
  <p>When inserting a dataset into an new row of this table I know all values in my C++ program exept the new primary key because the database creates it. How can I retrieve this key form the database?</p>
  
  <p>Maybe someone else inserted an entry too - just a moment after I inserted one. So retrieve the PK with the highest value could create an error. How can I handle this?</p>
  
  <hr>
  
  <p>Adopting Amir Rahimi Farahani's answer I found the following solution for my problem:</p>
  
  <p>I use a generator:</p>
  
  <pre><code>CREATE GENERATOR GEN_CHANNEL_PARAMETER_SET_ID;
  SET GENERATOR GEN_CHANNEL_PARAMETER_SET_ID TO 0;
  </code></pre>
  
  <p>and the following C++/IBPP/SQL code:</p>
  
  <pre><code>// SQL statement
  m_DbStatement-&gt;Execute(
      "SELECT NEXT VALUE FOR gen_channel_parameter_set_id FROM rdb$database"
      );
  
  // Retrieve Data
  IBPP::Row ibppRow;
  int64_t channelParameterSetId;
  
  m_DbStatement-&gt;Fetch(ibppRow);
  ibppRow-&gt;Get (1, channelParameterSetId);
  
  
  // SQL statement
  m_DbStatement-&gt;Prepare(
      "INSERT INTO channel_parameter_sets "
      "(channel_parameter_set_id, ...) "
      "VALUES (?, ...) " 
      );      
  
  // Set variables
  m_DbStatement-&gt;Set (1, channelParameterSetId);
  ...
  ...
  
  // Execute
  m_DbStatement-&gt;Execute ();
  m_DbTransaction-&gt;CommitRetain ();
  </code></pre>