SQLite
Selection
import sqlite3
# connect database
con = sqlite3.connect('/Applications/MAMP/db/sqlite/University')
# create cursor
cur = con.cursor()
# execute query
cur.execute("Select * from Department")
# fetch result
result = cur.fetchall()
print(result)
# close connection
con.close()
Join
import sqlite3
import pandas as pd
# connect database
con = sqlite3.connect('/Applications/MAMP/db/sqlite/University')
# create cursor
cur = con.cursor()
# execute query
cur.execute("select Department.Mgr_ssn, Dept_locations.Dlocation \
from Dept_locations, Department \
where Dept_locations.Dnumber = Department.Dnumber")
# fetch result
df = pd.DataFrame.from_records(cur.fetchall(), columns=['Manager_SSN', 'Department_Location'])
print(df)
# close connection
con.close()
Like
import sqlite3
import pandas as pd
# connect database
con = sqlite3.connect('/Applications/MAMP/db/sqlite/University')
# create cursor
cur = con.cursor()
# execute query
cur.execute("SELECT Fname, Lname, Dno\
from Employee \
where Employee.Fname like 'J%'")
# fetch result
df = pd.DataFrame.from_records(cur.fetchall(), columns=['First', 'Last', 'Dno'])
print(df)
# close connection
con.close()
Query Parameter
import sqlite3
import pandas as pd
# connect database
con = sqlite3.connect('/Applications/MAMP/db/sqlite/University')
# create cursor
cur = con.cursor()
# execute query
cur.execute("SELECT Fname, Lname, Dno\
from Employee \
where Employee.Dno = ? and Employee.Fname like ?", ('5', 'J%'))
# fetch result
df = pd.DataFrame.from_records(cur.fetchall(), columns=['First', 'Last', 'Dno'])
print(df)
# close connection
con.close()
Update
import sqlite3
import pandas as pd
# connect database
con = sqlite3.connect('/Applications/MAMP/db/sqlite/University')
# create cursor
cur = con.cursor()
cur.execute('PRAGMA foreign_keys = ON')
# execute query
cur.execute("Update Employee \
Set ssn = '987654321' \
WHERE Fname = 'Jennifer'")
# commit
con.commit()
# close connection
con.close()
Installation