Skip to content

Commit 1f8e7f6

Browse files
authored
Implement CRUD operations for employees
Added CRUD operations for employee records including insert, update, delete, and fetch all.
1 parent 4f1d151 commit 1f8e7f6

File tree

1 file changed

+60
-9
lines changed

1 file changed

+60
-9
lines changed

app.py

Lines changed: 60 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,65 @@
1-
from flask import Flask
2-
import os
1+
from flask import Flask, request, jsonify
2+
import mysql.connector
33

44
app = Flask(__name__)
55

6-
@app.route('/')
7-
def hello():
8-
return "Hello World!"
6+
def get_db():
7+
return mysql.connector.connect(
8+
host="localhost",
9+
user="your_user",
10+
password="your_password",
11+
database="your_database"
12+
)
913

10-
if __name__ == '__main__':
11-
port = os.environ.get('FLASK_PORT') or 8080
12-
port = int(port)
14+
# INSERT
15+
@app.route("/insert", methods=["POST"])
16+
def insert_row():
17+
data = request.json
18+
name = data.get("name")
19+
role = data.get("role")
1320

14-
app.run(port=port,host='0.0.0.0')
21+
conn = get_db()
22+
cursor = conn.cursor()
23+
cursor.execute("INSERT INTO employees (name, role) VALUES (%s, %s)", (name, role))
24+
conn.commit()
25+
26+
return jsonify({"message": "Row inserted", "id": cursor.lastrowid})
27+
28+
# UPDATE
29+
@app.route("/update/<int:emp_id>", methods=["PUT"])
30+
def update_row(emp_id):
31+
data = request.json
32+
name = data.get("name")
33+
role = data.get("role")
34+
35+
conn = get_db()
36+
cursor = conn.cursor()
37+
cursor.execute(
38+
"UPDATE employees SET name=%s, role=%s WHERE id=%s",
39+
(name, role, emp_id)
40+
)
41+
conn.commit()
42+
43+
return jsonify({"message": "Row updated"})
44+
45+
# DELETE
46+
@app.route("/delete/<int:emp_id>", methods=["DELETE"])
47+
def delete_row(emp_id):
48+
conn = get_db()
49+
cursor = conn.cursor()
50+
cursor.execute("DELETE FROM employees WHERE id=%s", (emp_id,))
51+
conn.commit()
52+
53+
return jsonify({"message": "Row deleted"})
54+
55+
# OPTIONAL: fetch all rows
56+
@app.route("/employees", methods=["GET"])
57+
def get_all():
58+
conn = get_db()
59+
cursor = conn.cursor(dictionary=True)
60+
cursor.execute("SELECT * FROM employees")
61+
rows = cursor.fetchall()
62+
return jsonify(rows)
63+
64+
if __name__ == "__main__":
65+
app.run(debug=True)

0 commit comments

Comments
 (0)