Get rowID of record being INSERTED into SQLite database
Posted: Sat Jan 16, 2021 10:36 pm
When I INSERT a new record into an SQLite database, is there a way to get the rowID of that record?
http://www.purebasic.com
https://www.purebasic.fr/english/
Code: Select all
select last_insert_rowid();Code: Select all
result = DatabaseUpdate(#dbaseID, "INSERT INTO command " +
"(category, cmd, syntax) " +
"VALUES (?, ?, ?);")
Code: Select all
DatabaseQuery(#dbaseID, "select last_insert_rowid();"
If NextDatabaseRow(#dbaseID)
Debug GetDatabaseLong(#dbaseID, 0)
EndIfCode: Select all
Procedure.l GetNextAutoIncIDForTable(DatabaseHandle, TableName.s)
Protected expr.s = "select seq + 1 as NextID from sqlite_sequence where lower(name) = lower(" + QuotedStr(TableName.s) + ")", result = -1
If DatabaseQuery(DatabaseHandle, expr)
If NextDatabaseRow(DatabaseHandle)
Result = GetDatabaseLong(DatabaseHandle, 0)
Else ; no entry in sequence table yet
Result = 1
EndIf
FinishDatabaseQuery(DatabaseHandle)
Else
; handle query error here
EndIf
ProcedureReturn result
EndProcedureHere is my answerColumbo wrote:When I INSERT a new record into an SQLite database, is there a way to get the rowID of that record?
Code: Select all
UseSQLiteDatabase()
If FileSize(GetTemporaryDirectory()+"toto.db") <> -1 And FileSize(GetTemporaryDirectory()+"toto.db") <> -2
DeleteFile(GetTemporaryDirectory()+"toto.db")
EndIf
If FileSize(GetTemporaryDirectory()+"toto.db") = -1
CreateFile(0, GetTemporaryDirectory()+"toto.db", #PB_UTF8 )
CloseFile(0)
EndIf
Global ouverture.l =OpenDatabase(#PB_Any, GetTemporaryDirectory()+"toto.db" , "", "", #PB_Database_SQLite )
Requete.s = "CREATE TABLE Cats( CatId INTEGER PRIMARY KEY, CatName);INSERT INTO Cats VALUES ( NULL, 'Brush' ),( NULL, 'Scarcat' ), ( NULL, 'Flutter' )"
DatabaseUpdate(ouverture,requete)
;====================================
; This instruction after an insert give the result you search
;====================================
DatabaseQuery(ouverture,"Select last_insert_rowid();")
NextDatabaseRow(ouverture)
Debug GetDatabaseLong(ouverture,0)
FinishDatabaseQuery(ouverture)
CloseDatabase(ouverture)