I created a table by following query:
with sqlite3.connect('example.db', detect_types=sqlite3.PARSE_DECLTYPES) as conn:
cur = conn.cursor()
cur.execute("CREATE TABLE Surveys(Id INTEGER PRIMARY KEY, Name TEXT, Desc TEXT, DictObject BLOB, Hash TEXT)")
conn.commit()
Now I have to add some Survey data to Surveys table for every request. Surveys table has Id as primary integer value. This has to be increased upon every insertion – And What is the proper way to do it? Do I have to fetch every row and check what the lastIdis upon every request?
sqlitewill automatically provide an id for a INTEGER PRIMARY KEY column on INSERT on a table if you do not provide a value yourself. Just insert data for every column except for theidcolumn.You may want to add the keyword
AUTOINCREMENTto youridcolumn though; the default is to pick the highest existing row id plus 1, and if you delete data from the table on a regular basis that can lead to reuse of ids (delete the current highest id and it’ll be re-used next time round).AUTOINCREMENTguarantees that each generated number will only be used once for a table, independent of deletes.Note that when you use a
sqlite3connection as a context manager (using thewithstatement), thecommit()is automatically applied for you. Quoting the documentation:In other words, you can safely remove the
conn.commit()line in your code, it is entirely redundant.