-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite_db.py
More file actions
50 lines (37 loc) · 1.75 KB
/
sqlite_db.py
File metadata and controls
50 lines (37 loc) · 1.75 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# sqlite is a simple local DB
# connecting/creating to/a local sqlite database
import sqlite3
# if DB exists, it connects to it;
# if DB doesn't exist, it will be created
connection = sqlite3.connect('mydbname.db')
cursor = connection.cursor()
# chose the column names and data type for each
cursor.execute('''CREATE TABLE IF NOT EXISTS mytablename
(col1 type1, col2 type2, col3 type3)''')
connection.commit()
connection.close()
# when you create the table, it would be best to have an autoincrementing primary key id
# use this for col1 type1 : id INTEGER PRIMARY KEY AUTOINCREMENT
-------------------------
## Additional commands (place them between curosr and connection.comit()
## Most commands must be run only once (so cursor + code + commit&close, save file and run)
## e.g. if you run insert multiple times, you'll just get duplicates (to automate you could use an if already exists)
# Insert (manual) values into table (text and data need ' ' )
cursor.execute("INSERT INTO mytablename VALUES ('Value1', 'Value2', 'Value3')")
# Insert (manual) multiple values at once into table
# declare a list of values, create a variable with it, insert it with ??? (for security purposes)
variablename = [('Value11', 'Value12', 'Value13'),
('Value21', 'Value22', 'Value23'),
('Value31', 'Value32', 'Value33')]
cursor.executemany('Insert INTO mytablename VALUES (?,?,?)', variablename)
## Cheking values
# we have multiple ways:
# a) fetch a single row
# b) iterate through every row
# c) fetch all results at once
cursor.execute("SELECT * FROM mytablename")
print(cursor.fetchone()) # fetches a single row
print(cursor.fetchall()) # fetches all rows
records = cursor.execute("SELECT * FROM Movies")
for record in records:
print(record)