You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The advantage to using a *row factory* is that you don't need to know the order of the columns in a
2416
+
table to access specific columns. You can instead simply use the column name.
2417
+
2304
2418
##### `Getting the column names from a table`
2305
2419
2306
2420
SQLite has a `PRAGMA` statement (often used as as a [table-valued function](https://www.sqlite.org/vtab.html#tabfunc2)) that allows you to query metadata about a table. Using `PRAGMA_TABLE_INFO` is a handy way to pull the column names (or other metadata about the columns such as column constraints) from a table using a simple `SELECT` query, as in the example below:
@@ -2325,6 +2439,60 @@ The `result` variable from the above query would have this form:
2325
2439
[('user_id',) ('username',) ('password',)]
2326
2440
```
2327
2441
2442
+
##### `Getting the primary key of last inserted row`
2443
+
2444
+
When using an `AUTOINCREMENT` constraint on a `PRIMARY KEY` column, you let the SQLite DB create the
2445
+
`PRIMARY KEY` for each row as they are inserted. This means you won't know the `PRIMARY KEY` if you
2446
+
need to use it in further statements after a row has been inserted in the DB.
2447
+
2448
+
Using the `cursor.lastrowid` property, you can get the `PRIMARY KEY` of the last row to be inserted
2449
+
in the DB and use it in further statements:
2450
+
2451
+
```python
2452
+
import sqlite3
2453
+
2454
+
connection = sqlite3.connect("users.sqlite")
2455
+
cursor = connection.cursor()
2456
+
2457
+
2458
+
defselect_all_users():
2459
+
query ="""
2460
+
SELECT * FROM users;
2461
+
"""
2462
+
2463
+
cursor.execute(query)
2464
+
results = cursor.fetchall()
2465
+
print(results)
2466
+
2467
+
2468
+
print("Results before INSERT")
2469
+
select_all_users()
2470
+
2471
+
2472
+
query ="""
2473
+
INSERT INTO users (username, password) VALUES ('steve', 'm!n3cr@ft');
2474
+
"""
2475
+
2476
+
cursor.execute(query)
2477
+
connection.commit()
2478
+
2479
+
print("Results after INSERT")
2480
+
select_all_users()
2481
+
2482
+
# Will give us the `user_id` of the last inserted user
2483
+
last_user_id = cursor.lastrowid
2484
+
2485
+
print(f"The ID of the last row inserted is: {last_user_id}")
0 commit comments