Skip to content

Commit dbd5fb3

Browse files
Merge pull request #170 from codewizardshq/add-sqlite-docs
Add `None`, `lastrowid`, and `sqlite3.Row` docs.
2 parents fe89081 + 605de63 commit dbd5fb3

File tree

1 file changed

+168
-0
lines changed

1 file changed

+168
-0
lines changed

docs/python/python-language.md

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -701,6 +701,41 @@ print(words2) ["I ", " coding so much!"]
701701

702702
```
703703

704+
705+
### `None`
706+
707+
The `None` data type represents the absence of a value. It is the default return value for any
708+
function without an explicit `return` statement:
709+
710+
```python
711+
def say_hi():
712+
print("Hello")
713+
# Nothing is returned here...
714+
715+
716+
# Nothing is returned from `say_hi()`, so `return_value` holds `None`
717+
return_value = say_hi()
718+
print(return_value) # None
719+
```
720+
721+
If you use a `return` statement to exit a function early, but don't explicitly provide a value for
722+
the `return` statement, `None` is also returned.
723+
724+
```python
725+
def divide(numerator, denominator):
726+
if denominator == 0:
727+
print("You can't divide by 0!")
728+
# Implicitly returns `None`
729+
return
730+
731+
return numerator / denominator
732+
733+
734+
quotient = divide(3, 0)
735+
print(quotient) # None
736+
```
737+
738+
704739
_Further Reading_
705740

706741
- [The Python Library Reference - Text Sequence Type](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str)
@@ -2301,6 +2336,85 @@ The `result` variable from the example above would have this form:
23012336
(1, 'djs', 'mypa$$word')
23022337
```
23032338

2339+
###### Using Row Factories
2340+
2341+
Usually, fetched records from a SQLite DB are returned as a `list` of `tuples`, as you can see in
2342+
the previous section. If you use a *row
2343+
factory*, you'll get a `list` of `sqlite3.Row` objects instead:
2344+
2345+
```python
2346+
import sqlite3
2347+
2348+
connection = sqlite3.connect("user-info.db")
2349+
2350+
# Allows us to get sqlite3.Row objects as results of queries
2351+
connection.row_factory = sqlite3.Row
2352+
2353+
cursor = connection.cursor()
2354+
2355+
query = """
2356+
SELECT * FROM users;
2357+
"""
2358+
2359+
cursor.execute(query)
2360+
results = cursor.fetchall()
2361+
2362+
for result in results:
2363+
print(result)
2364+
2365+
```
2366+
2367+
*output*
2368+
2369+
```text
2370+
<sqlite3.Row object at 0x7f82916e3c10>
2371+
<sqlite3.Row object at 0x7f8290367790>
2372+
<sqlite3.Row object at 0x7f8290367760>
2373+
```
2374+
2375+
These `sqlite3.Row` objects behave like `dict`s, so you can access the each resulting row using the
2376+
column name instead of the index number:
2377+
2378+
```python
2379+
import sqlite3
2380+
2381+
connection = sqlite3.connect("user-info.db")
2382+
connection.row_factory = sqlite3.Row
2383+
cursor = connection.cursor()
2384+
2385+
2386+
query = """
2387+
SELECT * FROM users;
2388+
"""
2389+
2390+
cursor.execute(query)
2391+
results = cursor.fetchall()
2392+
2393+
for result in results:
2394+
print(dict(result))
2395+
2396+
2397+
first_result = results[0]
2398+
2399+
print(f"user_id: {first_result['user_id']}")
2400+
print(f"username: {first_result['username']}")
2401+
print(f"password: {first_result['password']}")
2402+
```
2403+
2404+
*output*
2405+
2406+
```text
2407+
{'user_id': 1, 'username': 'djs', 'password': 'mypa$$word'}
2408+
{'user_id': 2, 'username': 'django', 'password': 'w0ff'}
2409+
{'user_id': 3, 'username': 'alecg', 'password': 'c0de'}
2410+
user_id: 1
2411+
username: djs
2412+
password: mypa$$word
2413+
```
2414+
2415+
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+
23042418
##### `Getting the column names from a table`
23052419

23062420
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:
23252439
[('user_id',) ('username',) ('password',)]
23262440
```
23272441

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+
def select_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}")
2486+
```
2487+
2488+
```text
2489+
Results before INSERT
2490+
[(1, 'djs', 'mypa$$word'), (2, 'django', 'w0ff'), (3, 'alecg', 'c0de')]
2491+
Results after INSERT
2492+
[(1, 'djs', 'mypa$$word'), (2, 'django', 'w0ff'), (3, 'alecg', 'c0de'), (4, 'steve', 'm!n3cr@ft')]
2493+
The ID of the last row inserted is: 4
2494+
```
2495+
23282496
_Further Reading_
23292497

23302498
- [The Python Standard Library - `sqlite3`](https://docs.python.org/3/library/sqlite3.html#module-sqlite3)

0 commit comments

Comments
 (0)