-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchapter11_sql.py
More file actions
25 lines (17 loc) · 849 Bytes
/
chapter11_sql.py
File metadata and controls
25 lines (17 loc) · 849 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import sqlite3
## this ensures that the queries' results (i.e., rows) have dictionary-like format
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
database_connection = sqlite3.connect('example.db')
database_connection.row_factory = dict_factory
cursor = database_connection.cursor()
## SQL commands end with the character ;
posts = cursor.execute("SELECT * FROM posts;").fetchall() ## execute a database command and store all the results in a variable
for row in posts:
print( row['text'] )
cursor.execute("""INSERT INTO posts(text) VALUES ("This post has no comments.");""") ## execute the command without storing the resulting values
database_connection.commit() ## store the changes made
database_connection.close() ## close the database connection