hahamed
hahamed

Reputation: 329

Is sqlite last_insert_rowid atomic?

I use node.js sqlite3 to manipulate data. I use these codes to insert data to database and get inserted id:

db.run("INSERT INTO myTable (name) VALUES ('test')");
db.get("SELECT last_insert_rowid() as id", function (err, row) {
     console.log('Last inserted id is: ' + row['id']);
});

I think this is not stable. my db connection is always open. when my server serves this code on multiple and same time connections from clients, DoesSELECT last_insert_rowid() get id rightly? Is sqlite last_insert_rowid atomic? thanks.

Upvotes: 13

Views: 14415

Answers (5)

Kiran Chenna
Kiran Chenna

Reputation: 1729

for Node.js Sqlite3 last inserted id you can use lastId

here is a simple Example

db.run("INSERT INTO foo ...", function(err) {
    if(null == err){
        // row inserted successfully
        console.log(this.lastID);
    } else {
        //Oops something went wrong
        console.log(err);
    }
});

Upvotes: 7

user2655879
user2655879

Reputation: 3

This.data.lastID will give you last inserted ID.

Upvotes: -1

Sachin Jain
Sachin Jain

Reputation: 139

try{

    db.run("INSERT INTO TABLE_NAME VALUES (NULL,?,?,?,?)",data1,data2,data3,data4,function(err){
                    if(err){
                        callback({"status":false,"val":err});
                    }else{
                        console.log("val  "+this.lastID);
                        callback({"status":true,"val":""});
                    }
                });
}catch(ex){
    callback({"status":false,"val":ex});
}

this.lastID return the last inserted row id By documentation sqlite3 Database#run(sql, [param, ...], [callback])

Upvotes: 13

Mikalai
Mikalai

Reputation: 1525

By documentation sqlite3 Database#run(sql, [param, ...], [callback]) you can retrive lastID from callback.

Upvotes: 11

sstn
sstn

Reputation: 3069

last_insert_rowid() returns the ROWID for the last insert operation on this connection.

The result is unpredictable if the function is called from multiple threads on the same database connection.

Documentation (for the C API): https://www.sqlite.org/c3ref/last_insert_rowid.html

If you don't share your database connection (session) between multiple threads for concurrent inserts, this is safe. If multiple threads insert on the same connection, this is unsafe, i.e. you might get either ID or a completely invalid ID.

Upvotes: 2

Related Questions