Skip to content

Commit 70edb18

Browse files
Merge pull request #168 from codewizardshq/add-more-sql-docs
Add docs about the `sqlite3` module to the Python Language Docs.
2 parents 926f46a + 50d8272 commit 70edb18

File tree

1 file changed

+196
-11
lines changed

1 file changed

+196
-11
lines changed

docs/python/python-language.md

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

702702
```
703703

704-
705-
706704
_Further Reading_
707705

708706
- [The Python Library Reference - Text Sequence Type](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str)
@@ -868,7 +866,6 @@ alecg is in the 'names' list
868866
samh is NOT in the 'names' list
869867
```
870868

871-
872869
#### Sorting a `list`
873870

874871
To sort the values in a list, use the `.sort()` method. The sort is in-place, which means it reorders the original list instead of making a copy:
@@ -880,7 +877,7 @@ names.sort()
880877
print(names) # ['alecg', 'danielj', 'dimas']
881878
```
882879

883-
You can pass keyword arguments to the `list.sort()` method to customize the way the `list` is sorted.
880+
You can pass keyword arguments to the `list.sort()` method to customize the way the `list` is sorted.
884881

885882
For example, the `key` argument can be a function to run on each item of the `list` before sorting:
886883

@@ -910,7 +907,6 @@ print(names) # ['dimas', 'danielj', 'alecg']
910907

911908
To see an alternative way of sorting, look up the built in `sorted()` function.
912909

913-
914910
_Further Reading_
915911

916912
- [The Python Library Reference - Common Sequence Operations](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations)
@@ -1320,11 +1316,11 @@ print(contents)
13201316
file.close()
13211317
```
13221318

1323-
| Mode | Meaning |
1324-
|------|--------------------------------------------------------------------------------------------|
1325-
| `"r"` | Read-only mode |
1326-
| `"w"` | Write mode. Will overwrite all data in the file or create a new one if it doesn't exist |
1327-
| `"a"` | Append mode. Will add data to the end of the file, or create a new one if it doesn't exist |
1319+
| Mode | Meaning |
1320+
| ----- | ------------------------------------------------------------------------------------------ |
1321+
| `"r"` | Read-only mode |
1322+
| `"w"` | Write mode. Will overwrite all data in the file or create a new one if it doesn't exist |
1323+
| `"a"` | Append mode. Will add data to the end of the file, or create a new one if it doesn't exist |
13281324

13291325
After you are finished with a file, call the `.close()` method.
13301326

@@ -1340,7 +1336,7 @@ for line in file:
13401336
counter += 1
13411337
if "taco" in line:
13421338
print(f"found taco on line {counter}")
1343-
1339+
13441340
print(f"there are {counter} lines in the file")
13451341
file.close()
13461342
```
@@ -2089,6 +2085,195 @@ _Further Reading_
20892085
- [The Python Standard Library](https://docs.python.org/3/library/index.html)
20902086
- [The Python Standard Library - `random`](https://docs.python.org/3/library/random.html)
20912087

2088+
#### sqlite3
2089+
2090+
The `sqlite3` module is used to interact with SQLite databases from Python. This section will focus on the `sqlite3` module, and won't go into much detail on the SQL language at all. If you're interested in understanding SQL, check out the [SQL Language Docs](https://docs.codewizardshq.com/sql/sql-language/).
2091+
2092+
The following examples will all reference a SQLite DB called `user-info.db` with a single table called `users` in the shape below:
2093+
2094+
```sql
2095+
┌─────────┬──────────┬────────────┐
2096+
│ user_id │ username │ password │
2097+
├─────────┼──────────┼────────────┤
2098+
1 │ djs │ mypa$$word │
2099+
├─────────┼──────────┼────────────┤
2100+
2 │ django │ w0ff │
2101+
├─────────┼──────────┼────────────┤
2102+
3 │ alecg │ c0de │
2103+
└─────────┴──────────┴────────────┘
2104+
```
2105+
2106+
##### `Connecting to a SQLite database from Python`
2107+
2108+
To use the `sqlite3` module, you must first import it:
2109+
2110+
```python
2111+
import sqlite3
2112+
```
2113+
2114+
Once the `sqlite3` module is imported, you'll want to connect to a SQLite database. SQLite databases are just plain files, and the file extension is irrelevant (some people use `.db`, others `.sqlite3`, etc.).
2115+
2116+
The `sqlite3.connect()` method is how you connect to a SQLite database. Note that it will create the database if it doesn't exist.
2117+
2118+
```python
2119+
import sqlite3
2120+
2121+
connection = sqlite3.connect("user-info.db")
2122+
```
2123+
2124+
Just like with files, you'll need to close the `connection` to a DB when you're done with it. The `connection.close()` method should be used for this purpose. Note that no further queries can be run against the DB after that line completes.
2125+
2126+
```python
2127+
import sqlite3
2128+
2129+
connection = sqlite3.connect("user-info.db")
2130+
2131+
# Do some stuff with the DB...
2132+
2133+
# When you're done with the DB connection, close it!
2134+
connection.close()
2135+
```
2136+
2137+
##### `Executing SQL statements from Python`
2138+
2139+
To execute a SQL statement from a Python script, you need to create a `cursor` from your `connection` using the `connection.cursor()` method:
2140+
2141+
```python
2142+
import sqlite3
2143+
2144+
connection = sqlite3.connect("user-info.db")
2145+
cursor = connection.cursor()
2146+
```
2147+
2148+
One you've created the `cursor` object, you can use the `cursor.execute()` method to execute a SQL `query` (in the form of a Python `str`) against the DB you've connected to:
2149+
2150+
```python
2151+
import sqlite3
2152+
2153+
connection = sqlite3.connect("user-info.db")
2154+
cursor = connection.cursor()
2155+
2156+
query = """
2157+
CREATE TABLE IF NOT EXISTS users (
2158+
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
2159+
username TEXT UNIQUE NOT NULL,
2160+
password TEXT NOT NULL
2161+
);
2162+
"""
2163+
2164+
cursor.execute(query)
2165+
```
2166+
2167+
##### `Modifying SQL DBs from Python`
2168+
2169+
If your query modifies the database (as `INSERT`, `UPDATE`, and `DELETE` queries do) you'll need to use the `connection.commit()` method to ensure the changes are stored in the DB:
2170+
2171+
```python
2172+
import sqlite3
2173+
2174+
connection = sqlite3.connect("user-info.db")
2175+
cursor = connection.cursor()
2176+
2177+
query = """
2178+
INSERT INTO users (username, password) VALUES ("alexg", "r@wkcl!m3");
2179+
"""
2180+
2181+
cursor.execute(query) # Careful! The changes aren't stored in the DB yet...
2182+
connection.commit() # Now, the changes are stored in the DB!
2183+
```
2184+
2185+
The DB would look like this after the changes above, note that user `alexg` has been added:
2186+
2187+
```sql
2188+
┌─────────┬──────────┬────────────┐
2189+
│ user_id │ username │ password │
2190+
├─────────┼──────────┼────────────┤
2191+
1 │ djs │ mypa$$word │
2192+
├─────────┼──────────┼────────────┤
2193+
2 │ django │ w0ff │
2194+
├─────────┼──────────┼────────────┤
2195+
3 │ alecg │ c0de │
2196+
├─────────┼──────────┼────────────┤
2197+
4 │ alexg │ r@wkcl!m3 │
2198+
└─────────┴──────────┴────────────┘
2199+
```
2200+
2201+
##### `Reading data from a SQL DB in Python`
2202+
2203+
If you need to read data from a DB, then you'll have to fetch the results from the `cursor`.
2204+
2205+
If you expect multiple results, `cursor.fetchall()` returns a `list` of `tuples`, where each `tuple` represents a row in the DB:
2206+
2207+
```python
2208+
import sqlite3
2209+
2210+
connection = sqlite3.connect("user-info.db")
2211+
cursor = connection.cursor()
2212+
2213+
query = """
2214+
SELECT * FROM users;
2215+
"""
2216+
2217+
cursor.execute(query)
2218+
results = cursor.fetchall()
2219+
```
2220+
2221+
The `results` variable from the example above would have this form:
2222+
2223+
```python
2224+
[(1, 'djs', 'mypa$$word'), (2, 'django', 'w0ff'), (3, 'alecg', 'c0de')]
2225+
```
2226+
2227+
If you want a single result (usally when using a `WHERE` clause with an `=` comparison), you use the `cursor.fetchone()` method to get a single `tuple` result representing the selection (one or more columns) from your query:
2228+
2229+
```python
2230+
import sqlite3
2231+
2232+
connection = sqlite3.connect("user-info.db")
2233+
cursor = connection.cursor()
2234+
2235+
query = """
2236+
SELECT * FROM users WHERE username = "djs";
2237+
"""
2238+
2239+
cursor.execute(query)
2240+
result = cursor.fetchone()
2241+
```
2242+
2243+
The `result` variable from the example above would have this form:
2244+
2245+
```python
2246+
(1, 'djs', 'mypa$$word')
2247+
```
2248+
2249+
##### `Getting the column names from a table`
2250+
2251+
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:
2252+
2253+
```python
2254+
import sqlite3
2255+
2256+
connection = sqlite3.connect("user-info.db")
2257+
cursor = connection.cursor()
2258+
2259+
query = """
2260+
SELECT name AS column_name FROM PRAGMA_TABLE_INFO("users");
2261+
"""
2262+
2263+
cursor.execute(query)
2264+
result = cursor.fetchall()
2265+
```
2266+
2267+
The `result` variable from the above query would have this form:
2268+
2269+
```python
2270+
[('user_id',) ('username',) ('password',)]
2271+
```
2272+
2273+
_Further Reading_
2274+
2275+
- [The Python Standard Library - `sqlite3`](https://docs.python.org/3/library/sqlite3.html#module-sqlite3)
2276+
20922277
<hr>
20932278

20942279
## The `pass` statement

0 commit comments

Comments
 (0)