Skip to content

Commit ba9f603

Browse files
committed
Using employee class with sqlite database
1 parent 6e7f47a commit ba9f603

2 files changed

Lines changed: 55 additions & 2 deletions

File tree

employees2.db

1 KB
Binary file not shown.

python_sqlite2.py

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,71 @@
11
import sqlite3
2+
from employees import Employee
23

34
conn = sqlite3.connect('employees2.db')
45

56
c = conn.cursor()
67

7-
#c.execute("""CREATE TABLE employees3 (
8+
#c.execute("""CREATE TABLE employees4 (
89
# first text,
910
# last text,
1011
# pay integer
1112
# )""")
1213

1314

14-
c.execute("INSERT INTO employees3 VALUES ('Sheldon', 'Cooper', '50000')")
15+
def insert_employee(emp):
16+
with conn:
17+
c.execute("INSERT INTO employees4 VALUES (?, ?, ?)", (emp.first, emp.last, emp.pay))
1518

19+
def get_emp_by_lastname(lastname):
20+
c.execute("SELECT * FROM employees4 WHERE last=?", (lastname,))
21+
print(c.fetchall())
22+
23+
def update_pay(emp, pay):
24+
with conn:
25+
emp.pay = pay
26+
c.execute("UPDATE employees4 SET pay=(?) WHERE first=(?) AND last=(?)", (emp.pay, emp.first, emp.last))
27+
28+
def delete_employee(emp):
29+
with conn:
30+
c.execute("DELETE FROM employees4 WHERE first=? AND last=?", (emp.first, emp.last))
31+
32+
33+
e1 = Employee('Caroline', 'Channing', 30000)
34+
e2 = Employee('Max', 'Black', '30000')
35+
36+
37+
# Following way of passing input to sql leads to sql injection attack
38+
# So it is not advised to pass arguments using string formatting to sqlite
39+
# c.execute("INSERT INTO employees3 VALUES ({}, {}, {}).format(e1.first, e1.last, e1.pay)")
40+
41+
insert_employee(e1)
42+
insert_employee(e2)
43+
44+
# In this way we are passing arguments as tuple, if we dont want to pass any value
45+
# We have to still pass it as tuple for example, if we only want to send first name they statement would be
46+
# c.execute("INSERT INTO employees3 VALUES (?, ?, ?)", (e1.first,))
47+
#c.execute("INSERT INTO employees3 VALUES (?, ?, ?)", (e1.first, e1.last, e1.pay))
48+
49+
# Other way to pass values is using dictionary
50+
#c.execute("INSERT INTO employees3 VALUES (:first, :last, :pay)", {'first':e2.first, 'last':e2.last, 'pay':e2.pay})
51+
52+
#c.execute("SELECT * FROM employees3 WHERE last=?", ('Dennings',))
53+
#print(c.fetchall())
54+
55+
#c.execute("SELECT * FROM employees3 WHERE last=:last", {'last':'Holmes'})
56+
#print(c.fetchall())
57+
58+
get_emp_by_lastname('Channing')
59+
60+
update_pay(e1, 40000)
61+
62+
delete_employee(e2)
63+
64+
c.execute("SELECT * FROM employees4")
65+
print(c.fetchall())
66+
67+
# Select statements doesn't need to be commited
68+
# INSERT statemets need to be commit
1669
conn.commit()
1770

1871
conn.close()

0 commit comments

Comments
 (0)