-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_python-sqlite.py
72 lines (54 loc) · 1.66 KB
/
_python-sqlite.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def create_table(conn, create_table_sql):
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
return None
def create_row(conn, create_row_sql, values):
try:
cur = conn.cursor()
cur.execute(create_row_sql, values)
except Error as e:
print(e)
def select_all_employees(conn):
cur = conn.cursor()
cur.execute("SELECT * FROM Employee")
rows = cur.fetchall()
for row in rows:
print(row)
def main():
database = "db.db"
sql_create_employee_table = """
CREATE TABLE IF NOT EXISTS Employee(
ID INTEGER PRIMARY KEY NOT NULL ,
Fname TEXT NOT NULL ,
Lname TEXT NOT NULL
);
"""
sql_create_employee_row = "INSERT OR IGNORE INTO Employee(ID, Fname, Lname) VALUES(?, ?, ?);"
# create a database connection
conn = create_connection(database)
# create tables
if conn is not None:
# create employee table
create_table(conn, sql_create_employee_table)
else:
print("Error! DB connection unsuccessful.")
with conn:
# create a new employee
values = (1, "ALYSSON", "ALVARAN")
create_row(conn, sql_create_employee_row, values)
# select all employees
select_all_employees(conn)
if __name__ == '__main__':
main()