-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbhelper.py
56 lines (50 loc) · 1.77 KB
/
dbhelper.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
import mysql.connector as connector
class DBHelper:
def __init__(self):
self.con = connector.connect(host='localhost',
port='3306',
user='root',
password='pawangupta2003',
database='pythontest'
)
query = 'create table if not exists user(userId int primary key,userName varchar(200), phone varchar(12))'
cur = self.con.cursor()
cur.execute(query)
print('created')
# Insert
def insert_user(self, userid, username, phone):
query = "insert into user(userId, userName, phone) values('{}', '{}', '{}')".format(
userid, username, phone)
# print(query)
cur = self.con.cursor()
cur.execute(query)
self.con.commit()
print('user saved to db')
# Fetch All
def fetch_all(self):
query = "select * from user"
cur = self.con.cursor()
cur.execute(query)
for row in cur:
print("UserId: ", row[0])
print("UserName: ", row[1])
print("Phone: ", row[2])
print()
print()
# Delete
def delete_user(self, userId):
query = "delete from user where userId= {}".format(userId)
# print(query)
c = self.con.cursor()
c.execute(query)
self.con.commit()
print("deleted")
# Update
def update_User(self, userId, newName, newPhone):
query = "update user set userName='{}',phone='{}'where userId={}".format(
newName, newPhone, userId)
# print(query)
cur = self.con.cursor()
cur.execute(query)
self.con.commit()
print("Updated")