Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite. How to get value of Auto Increment Primary Key after Insert, other than last_insert_rowid()?

I am using Sqlite3 with Flask microframework, but this question concerns only the Sqlite side of things..

Here is a snippet of the code:

g.db.execute('INSERT INTO downloads (name, owner, mimetype) VALUES (?, ?, ?)', [name, owner, mimetype]) file_entry = query_db('SELECT last_insert_rowid()') g.db.commit() 

The downloads table has another column with the following attributes: id integer primary key autoincrement,

If two people write at the same time the code above could produce errors.

Transactions can be messy. In Sqlite is there a neat built in way of returning the primary key generated after doing an INSERT ?

like image 776
Jon Cox Avatar asked Aug 09 '10 16:08

Jon Cox


People also ask

Does primary key auto increment SQLite?

On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually one more than the largest ROWID currently in use. This is true regardless of whether or not the AUTOINCREMENT keyword is used.

When you insert a new row into a SQLite database it automatically generates a value for?

If you don't specify the rowid value or you use a NULL value when you insert a new row, SQLite automatically assigns the next sequential integer, which is one larger than the largest rowid in the table. The rowid value starts at 1.

How do I find the last row ID in SQLite?

In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

Does SQLite support GUID?

SQLite itself does not support GUID as internal type.


1 Answers

The way you're doing it is valid. There won't be a problem if the above snipped is executed concurrently by two scripts. last_insert_rowid() returns the rowid of the latest INSERT statement for the connection that calls it. You can also get the rowid by doing g.db.lastrowid.

like image 118
reko_t Avatar answered Sep 19 '22 03:09

reko_t