As long as the database connection hasn't been closed
since the last insert operation, this is how I do it in
VB.NET:
Public Shared Function lastInsertID_openCon(ByRef myConnection As MySqlConnection) As Long
Dim id As Long = -1
Dim myDataSet As New DataSet
Dim sql As String = "SELECT LAST_INSERT_ID()"
Dim myCommand As New MySqlDataAdapter(sql, myConnection)
Dim objCmd As MySqlCommand
Dim objDR As MySqlDataReader
objCmd = New MySqlCommand(sql, myConnection)
objDR = objCmd.ExecuteReader(CommandBehavior.CloseConnecti on)
If Not (objDR Is Nothing) And objDR.Read = True Then
id = objDR.GetInt64(0)
Else
id = -1
End If
objDR.Close()
'Remember to close the connection!
Return id
End Function
If the database connection was closed after the insert
operation prior to calling this function then LAST_INSERT_ID returns garbage.
You're playing with fire if you do something like
SELECT max(ID) from sometable;
-lv