SQLコマンドを制御できる場合は、次のようなlast_insert_rowid
SQL関数を使用できます。
INSERT INTO Log(action) VALUES(42);
INSERT INTO ErrorExtras(pid, msg) VALUES(last_insert_rowid(), 'x');
(ただし、これは次のコマンドでのみ機能します。これは、INSERT
後でレコードlast_insert_rowid()
のを返すためです。)rowid
ErrorExtras
C APIを使用している場合は、次のsqlite3_last_insert_rowid
関数を使用できます。
sqlite3_prepare_v2(db, "INSERT INTO Log(action) VALUES(42)", -1, &stmt, NULL);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_prepare_v2(db, "INSERT INTO ErrorExtras(pid,msg) VALUES(?,?)", -1, &stmt, NULL);
sqlite3_bind_int64(stmt, 1, sqlite3_last_insert_rowid(db));
sqlite3_bind_text(stmt, 2, "x", -1, SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
他の言語のAPIには、通常、最後に挿入されたを取得するためのメカニズムもありますrowid
。たとえば、Androidでは、insert
関数はそれを返します。
ContentValues cv = new ContentValues();
cv.put("action", 42);
long log_rowid = db.insert("Log", null, cv);
ContentValues cv = new ContentValues();
cv.put("pid", log_rowid);
cv.put("msg", "x");
db.insert("ErrorExtras", null, cv);