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