Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/sqlite - selecting records after insert

Tags:

sqlite

Is there an sqlite equivalent to INSERT...;SELECT @@IDENTITY? If so, please show me the code or point me towards it.

Thanks!

like image 591
javovo Avatar asked Jun 09 '10 16:06

javovo


People also ask

How do I SELECT specific data in SQLite?

To select data from an SQLite database, use the SELECT statement. When you use this statement, you specify which table/s to select data from, as well as the columns to return from the query. You can also provide extra criteria to further narrow down the data that is returned.

How do I insert data into a SQLite database in Python?

Inserting data using pythonImport sqlite3 package. Create a connection object using the connect() method by passing the name of the database as a parameter to it. The cursor() method returns a cursor object using which you can communicate with SQLite3.

What is Fetchall in SQLite?

The sqlite3. Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones).


2 Answers

Cursor.lastrowid

>>> import sqlite3
>>> conn = sqlite3.connect(":memory:")
>>> c = conn.cursor()
>>> c.execute("create table t (id integer, some text);")
<sqlite3.Cursor object at 0x00C64CE0>
>>> c.execute("insert into t values(1,'a');")
<sqlite3.Cursor object at 0x00C64CE0>
>>> c.lastrowid
1
like image 105
mechanical_meat Avatar answered Sep 29 '22 16:09

mechanical_meat


SELECT last_insert_rowid() -- same as select @@identity

last_insert_rowid() The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

like image 24
Pranay Rana Avatar answered Sep 29 '22 18:09

Pranay Rana