Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in sqlite3, can a select succeed within a transaction of insert?

I begin a transaction, which is to insert several records into a table. Can I select the latest inserted record out of the database before the transaction commit?

like image 696
user26404 Avatar asked Dec 18 '08 02:12

user26404


2 Answers

Yes.

Inside a transaction, your application sees everything.

No other transaction, however, sees any part of the change.

The point of a transaction is to make a sequence of statements appear to be one atomic change to the database.

If you commit, all statements in the transaction are finalized, and everyone else can see the effects.

If you rollback, no statement in the transaction is finalized, and no change occurs to the database.

Not all statements can be part of a transaction, BTW. DDL (Create and Drop, for example) will end any previous transaction.

like image 181
S.Lott Avatar answered Oct 13 '22 00:10

S.Lott


Yes, during or after the transaction you can use the last_insert_rowid() function.

The last_insert_rowid() function returns the ROWID of the last row inserted from the database connection which invoked the function.

In other words:

SQLite version 3.6.23
Enter ".help" for instructions
Enter SQL statements terminated with a ";"

sqlite> create table T (C);
sqlite> insert into T values ('hello');
sqlite> select last_insert_rowid();
1
sqlite> BEGIN;
sqlite> insert into T values ('test 2');
sqlite> select last_insert_rowid();
2
sqlite> select rowid,* from T;
1|hello
2|test 2
sqlite> ROLLBACK;
sqlite> select last_insert_rowid();
2
sqlite> select rowid,* from T;
1|hello
sqlite>
like image 41
Noah Avatar answered Oct 13 '22 00:10

Noah