|
1 | 1 | import sqlite3 |
| 2 | +from employees import Employee |
2 | 3 |
|
3 | 4 | conn = sqlite3.connect('employees2.db') |
4 | 5 |
|
5 | 6 | c = conn.cursor() |
6 | 7 |
|
7 | | -#c.execute("""CREATE TABLE employees3 ( |
| 8 | +#c.execute("""CREATE TABLE employees4 ( |
8 | 9 | # first text, |
9 | 10 | # last text, |
10 | 11 | # pay integer |
11 | 12 | # )""") |
12 | 13 |
|
13 | 14 |
|
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)) |
15 | 18 |
|
| 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 |
16 | 69 | conn.commit() |
17 | 70 |
|
18 | 71 | conn.close() |
0 commit comments