title: How to retrieve the last autoincremented ID from a SQLite table?
body: <p>I have a table Messages with columns ID (primary key, autoincrement) and Content (text).<br/>
  I have a table Users with columns username (primary key, text) and Hash.<br/>
  A message is sent by one Sender (user) to many recipients (user) and a recipient (user) can have many messages.<br/>
  I created a table Messages_Recipients with two columns: MessageID (referring to the ID column of the Messages table and Recipient (referring to the username column in the Users table). This table represents the many to many relation between recipients and messages.<p>
  So, the question I have is this. The ID of a new message will be created after it has been stored in the database. But how can I hold a reference to the MessageRow I just added in order to retrieve this new MessageID? <br/> I can always search the database for the last row added of course, but that could possibly return a different row in a multithreaded environment?</p>
  
  <p>EDIT: As I understand it for SQLite you can use the <code>SELECT last_insert_rowid()</code>. But how do I call this statement from ADO.Net?</p>
  
  <p>My Persistence code (messages and messagesRecipients are DataTables):</p>
  
  <pre class="lang-csharp prettyprint-override"><code>public void Persist(Message message)
  {
      pm_databaseDataSet.MessagesRow messagerow;
      messagerow=messages.AddMessagesRow(message.Sender,
                              message.TimeSent.ToFileTime(),
                              message.Content,
                              message.TimeCreated.ToFileTime());
      UpdateMessages();
      var x = messagerow;//I hoped the messagerow would hold a
      //reference to the new row in the Messages table, but it does not.
      foreach (var recipient in message.Recipients)
      {
          var row = messagesRecipients.NewMessages_RecipientsRow();
          row.Recipient = recipient;
          //row.MessageID= How do I find this??
          messagesRecipients.AddMessages_RecipientsRow(row);
          UpdateMessagesRecipients();//method not shown
      } 
  
  }
  
  private void UpdateMessages()
  {
      messagesAdapter.Update(messages);
      messagesAdapter.Fill(messages);
  }
  </code></pre>