create database hr
CREATE TABLE employees ( id INTEGER PRIMARY KEY AUTO_INCREMENT, fullname VARCHAR (30) NOT NULL, job VARCHAR (20), salary INTEGER );
insert into employees(fullname,job,salary) values('Andy Roberts','Programmer',1500000); insert into employees(fullname,job,salary) values('Scott Guthrie','Programmer',2000000); insert into employees(fullname,job,salary) values('Kevin Loney','DBA',2500000); insert into employees(fullname,job,salary) values('Joe Stagner','Team Lead',4500000);
>pip install mysql-connector-python
{ "host": "localhost", "port": 3306, "database": "hr", "user": "root", "password": "mysql" }
import mysql.connector import json f = open("connection.json") # Open connection properties config = json.loads(f.read()) # Convert JSON to dict try: con = mysql.connector.connect(**config) # Unpack dict and pass to connect method print("Connected Successfully!") except Exception as ex: print("Connection Error : ", ex) finally: if con.is_connected(): con.close()
import mysql.connector import json f = open("connection.json") # Open connection properties config = json.loads(f.read()) # Convert JSON to dict try: con = mysql.connector.connect(**config) cur = con.cursor() cur.execute("select * from employees order by id") for id, name, job, salary in cur.fetchall(): print(f"{id:2} {name:20} {job:10} {salary:10}") cur.close() except Exception as ex: print("Error : ", ex) finally: if con.is_connected(): con.close()
import mysql.connector import json f = open("connection.json") # Open connection properties config = json.loads(f.read()) # Convert JSON to dict try: con = mysql.connector.connect(**config) cur = con.cursor() name = input("Enter name : ") job = input("Enter job : ") salary = int(input("Enter salary : ")) try: cur.execute("insert into employees (fullname,job,salary) values (%s,%s,%s)",(name, job, salary)) print("Added Employee Successfully!") con.commit() # Must call commit() to commit insertion except Exception as ex: print("Insertion Error : ", ex) finally: cur.close() except Exception as ex: print("Connection Error : ", ex) finally: if con.is_connected(): con.close()
import mysql.connector import json f = open("connection.json") # Open connection properties config = json.loads(f.read()) # Convert JSON to dict try: con = mysql.connector.connect(**config) cur = con.cursor() id = input("Enter id : ") salary = input("Enter salary : ") try: cur.execute("update employees set salary = %s where id = %s", (salary, id,)) if cur.rowcount == 1: # if id found and row updated print("Updated Employee Successfully!") con.commit() else: print("Sorry! Employee ID not found!") except Exception as ex: print("Update Error : ", ex) finally: cur.close() except Exception as ex: print("Connection Error : ", ex) finally: if con.is_connected(): con.close()
import mysql.connector import json f = open("connection.json") # Open connection properties config = json.loads(f.read()) # Convert JSON to dict try: con = mysql.connector.connect(**config) cur = con.cursor() id = input("Enter id : ") try: cur.execute("delete from employees where id = %s", (id,)) if cur.rowcount == 1: print("Deleted Employee Successfully!") con.commit() else: print("Sorry! Employee ID not found!") except Exception as ex: print("Deletion Error : ", ex) finally: cur.close() except Exception as ex: print("Connection Error : ", ex) finally: if con.is_connected(): con.close()
import mysql.connector import json f = open("connection.json") # Open connection properties config = json.loads(f.read()) # Convert JSON to dict try: con = mysql.connector.connect(**config) cur = con.cursor() cur.execute("select avg(salary), count(salary) from employees") summary = cur.fetchone() print(f"Average Salary : {summary[0]:8.0f}") print(f"Employee Count : {summary[1]:8}") cur.close() except Exception as ex: print("Error : ", ex) finally: if con.is_connected(): con.close()
1,2900000 2,3900000 11,1000000 4,4500000
import mysql.connector import json f = open("connection.json") # Open connection properties config = json.loads(f.read()) # Convert JSON to dict try: f = open('salaries.txt', 'rt') con = mysql.connector.connect(**config) cur = con.cursor() employees = [] for line in f.readlines(): parts = line.strip().split(",") if len(parts) != 2: continue # Ignore line id, salary = parts employees.append((salary, id)) f.close() try: cur.executemany("update employees set salary = %s where id = %s", employees) print(f"Updated {cur.rowcount} rows!") con.commit() except Exception as ex: print("Updation error : ", ex) finally: cur.close() except Exception as ex: print("Connection error : ", ex) finally: if con.is_connected(): con.close()
import mysql.connector import json f = open("connection.json") # Open connection properties config = json.loads(f.read()) # Convert JSON to dict try: con = mysql.connector.connect(**config) cur = con.cursor() cur.execute("select * from employees") employees = [] for id, name, job, salary in cur.fetchall(): empdict = {"id": id, "name": name, "job": job, "salary": salary} employees.append(empdict) print(json.dumps(employees)) cur.close() except Exception as ex: print("Error : ", ex) finally: if con.is_connected(): con.close()