SQLite
interface is built into Python as sqlite3 module!
Establish connection
import sqlite3
con = sqlite3.connect('cool.db')
# thanks to this db queries accessible as row objects -> behaves as dict!
con.row_factory = sqlite3.Row
cursor = con.cursor()
Create table
table_name = 'COOL_TABLE'
schema = []
schema.append("ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL")
schema.append("NAME TEXT")
schema.append("AGE INTEGER")
schema.append("IS_COOL BOOLEAN")
schema.append("RECORD_TIMESTAMP DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL")
query = "CREATE TABLE IF NOT EXISTS {}({})".format(table_name, ", ".join(schema))
cursor.execute(query)
Insert
query = fr""" INSERT INTO {table_name} ('NAME', 'AGE', 'IS_COOL') VALUES ('Bob', 40, 1) """
cursor.execute(query)
con.commit() # saves changes
Select
query = fr""" SELECT * FROM {table_name} WHERE IS_COOL = 1 """ # sqlite stores bools as 0/1
result = cursor.execute(query)
people = result.fetchall()
for person in people:
print(person['name'])
Update
query = fr""" UPDATE {table_name} SET IS_COOL = 0 WHERE NAME = 'Bob' """
cursor.execute(query)
con.commit()
Delete
query = fr""" DELETE FROM {table_name} WHERE NAME = 'Bob' """
cursor.execute(query)
con.commit()
Close connection
con.close()