【SQlite】 .lastrowidの使い方は?どういう意味?徹底解説!【python】

0. 背景

どうも。python独学勉強中のものです。自作webアプリを勉強中に、「.lastrowid」なるものにぶつかり、調べたところ日本語の解説がなかったので、ここにメモしておきます。

1. 結論

先に結論から申しますと、、、

.lastrowid とは、SQL文で最後にInsertされた列で定義されたIDを返すというものです。

まあよくわからないと思うので、実際に見てみましょう。

試しにやってみる

SQLiteをimportし、簡易的なテーブルを作り試してみます。

以下ソースコード。

import sqlite3 as lite

con = lite.connect(':memory:')

with con:

    cur = con.cursor()
    cur.execute("CREATE TABLE friends(id INTEGER PRIMARY KEY, name TEXT);")
    cur.execute("INSERT INTO friends(name) VALUES ('Tom');")
    cur.execute("INSERT INTO friends(name) VALUES ('Rebecca');")
    cur.execute("INSERT INTO friends(name) VALUES ('Jim');")
    cur.execute("INSERT INTO friends(name) VALUES ('Robert');")

    last_row_id = cur.lastrowid
    print ("The last Id of the inserted row is {}".format(last_row_id))
    

実行結果↓↓

The last Id of the inserted row is 4

「4」となりました。

この4は最後のinset文(以下)の固有 id になります。

cur.execute("INSERT INTO friends(name) VALUES ('Robert');")

補足

ここでの固有IDですが、SQLでinsert文を実行したときに自動的に割り振られるものです。

CREATE TABLE friends(id INTEGER PRIMARY KEY, name TEXT);

で、id をprimary key と設定しているからですね。

(余談ですが、今はidとしていますが、好きなものに変えても大丈夫です。)

本当に最後のinsert文なのか、念のため確認

まだ、この4が本当に最後のinsert文になっているか、確かめられていないので文を追加して再実行。

以下ソースコード

import sqlite3 as lite

con = lite.connect(':memory:')

with con:

    cur = con.cursor()
    cur.execute("CREATE TABLE friends(id INTEGER PRIMARY KEY, name TEXT);")
    cur.execute("INSERT INTO friends(name) VALUES ('Tom');")
    cur.execute("INSERT INTO friends(name) VALUES ('Rebecca');")
    cur.execute("INSERT INTO friends(name) VALUES ('Jim');")
    cur.execute("INSERT INTO friends(name) VALUES ('Robert');")

    last_row_id = cur.lastrowid
    print ("The last Id of the inserted row is {}".format(last_row_id))
    
    cur.execute("INSERT INTO friends(name) VALUES ('Jim');")
    cur.execute("INSERT INTO friends(name) VALUES ('Robert');")

    last_row_id = cur.lastrowid
    print ("The last Id of the inserted row is {}".format(last_row_id))

以下実行結果↓↓

The last Id of the inserted row is 4
The last Id of the inserted row is 6

既存のソースに、2行追加したら、結果6になりました。

間違いなさそうですね。

まとめ

以上、.lastrowidの解説でした。

最後のinsert文のid(primary key)を持ってくるものなので、insert文一つに対しlastrowidをつけておけば、insertした列の固有idがわかる。という使い方もできそうですね👍

参考

SQLite Python - SQLite programming in Python (zetcode.com)

(Visited 57 times, 1 visits today)

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA