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
|`"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 |
1328
1324
1329
1325
After you are finished with a file, call the `.close()` method.
1330
1326
@@ -1340,7 +1336,7 @@ for line in file:
1340
1336
counter +=1
1341
1337
if"taco"in line:
1342
1338
print(f"found taco on line {counter}")
1343
-
1339
+
1344
1340
print(f"there are {counter} lines in the file")
1345
1341
file.close()
1346
1342
```
@@ -2089,6 +2085,195 @@ _Further Reading_
2089
2085
-[The Python Standard Library](https://docs.python.org/3/library/index.html)
2090
2086
-[The Python Standard Library - `random`](https://docs.python.org/3/library/random.html)
2091
2087
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:
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)
0 commit comments