· 7 years ago · Nov 11, 2018, 02:12 PM
1import sqlite3
2from sqlite3 import Error
3
4def create_connection(db_file):
5 try:
6 conn = sqlite3.connect(db_file)
7 return conn
8 except Error as e:
9 print(e)
10 return None
11
12def create_table(conn,table,column):
13 cursor = conn.cursor()
14 query = "CREATE TABLE IF NOT EXISTS {} ({}) ".format(table, column)
15 print(query)
16 try:
17 cursor.execute(query)
18 except Exception as e:
19 print("Something went wrong, Details: {}".format(e))
20 else:
21 conn.commit()
22 print("A Table created successfully")
23
24def select_data(conn,column, table, condition=None, fetchall=False):
25 cursor = conn.cursor()
26 query = "SELECT {} FROM {} ".format(column, table)
27 if condition is not None:
28 query += "WHERE {}".format(condition)
29 print(query)
30 try:
31 cursor.execute(query)
32 except Exception as e:
33 print("Something went wrong, Details: {}".format(e))
34 else:
35 if fetchall:
36 result = cursor.fetchall()
37 return result
38 else:
39 result = cursor.fetchone()
40 return result
41
42def insert_date(conn,table, column, value):
43 cursor = conn.cursor()
44 query = "INSERT INTO {} ({}) VALUES ({}) ".format(table, column, value)
45 print(query)
46 try:
47 cursor.execute(query)
48 except Exception as e:
49 print("Something went wrong, Details: {}".format(e))
50 else:
51 conn.commit()
52 print("A row has been inserted successfully")
53
54def update_data(conn,table,column, condition=None):
55 cursor = conn.cursor()
56 query = 'UPDATE {} SET {} ' .format(table,column)
57 if condition is not None:
58 query+='WHERE {}'.format(condition)
59 print(query)
60 try:
61 cursor.execute(query)
62 except Exception as e:
63 print("Something went wrong, Details: {}".format(e))
64 else:
65 conn.commit()
66def delete_data(conn,table, condition):
67 cursor = conn.cursor()
68 query = 'DELETE FROM {} WHERE {}'.format(table, condition)
69 print(query)
70 try:
71 cursor.execute(query)
72 except Exception as e:
73 print("Something went wrong, Details: {}".format(e))
74 else:
75 conn.commit()