Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python + MySql Connectivity

The document provides Python code examples for connecting to MySQL databases and performing various operations such as creating tables, inserting records, and retrieving data based on specific criteria. It includes detailed instructions for creating a 'students' table in a 'school' database, adding items to a 'STATIONERY' table, and fetching employee and student details based on department and course respectively. Each section includes connection details, SQL queries, and expected outputs for clarity.

Uploaded by

Himanshu Tonk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python + MySql Connectivity

The document provides Python code examples for connecting to MySQL databases and performing various operations such as creating tables, inserting records, and retrieving data based on specific criteria. It includes detailed instructions for creating a 'students' table in a 'school' database, adding items to a 'STATIONERY' table, and fetching employee and student details based on department and course respectively. Each section includes connection details, SQL queries, and expected outputs for clarity.

Uploaded by

Himanshu Tonk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Python + MYSQL Connectivity

1. Write a Python program that connects to a MySQL database named school. Create a
table called students with the following structure:
host = localhost, username = admin, password = 1234
Field Type
id INT
name VARCHAR(50)
age INT
grade VARCHAR(10)
Insert one record in the table after creation. Ensure that the table is created only if it
does not already exist.
import mysql.connector
try:
connection = mysql.connector.connect(
host = "localhost",
user = "Admin",
passwd = "1234",
database = "school"
)

if connection.is_connected():
print("Connected to the database.")

cursor = connection.cursor()

query= """CREATE TABLE IF NOT EXISTS students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT,
grade VARCHAR(10)
)
"""
cursor.execute(query)
print("Table 'students' created or already exists.")

insert_query = """
INSERT INTO students (name, age, grade)
VALUES ('John Doe', 16, '10th')
"""
cursor.execute(insert_query)
connection.commit()
print("One record inserted into 'students' table.")

except mysql.connector.Error as err:


print(f"Error: {err}")

finally:
# Close the connection
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
Output:
Connected to the database.
Table 'students' created or already exists.
One record inserted into 'students' table.
Database connection closed.

2. A table, named STATIONERY, in ITEMDB database, has the following structure:


Field Type
itemNo int(11)
itemName varchar(15)
price float
Qty int(11)
Write the following Python function to perform the specified operation:
AddAndDisplay(): To input details of an item and store it in the tableSTATIONERY.
The function should then retrieve and display all records from the STATIONERY
table where the Price is greater than 120.
Assume the following for Python-Database connectivity:
Host: localhost, User: root, Password: Pencil

def AddAndDisplay():
import mysql.connector as mycon
mydb = mycon.connect(
host="localhost",
user="root",
passwd="Pencil",
database="ITEMDB"
)
mycur = mydb.cursor()
no = int(input("Enter Item Number: "))
nm = input("Enter Item Name: ")
pr = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
query = "INSERT INTO stationery VALUES ({}, '{}', {}, {})"
query = query.format(no, nm, pr, qty)
mycur.execute(query)
mydb.commit()
mycur.execute("SELECT * FROM stationery WHERE price > 120")
for rec in mycur:
print(rec)
mycur.close()
mydb.close()
Output:
Enter Item Number: 101
Enter Item Name: Notebook
Enter Price: 150
Enter Quantity: 20

(101, 'Notebook', 150.0, 20)

3. Write a Python program to connect to a MySQL database and print the details of
employees belonging to a specific department provided by the user.
Use the following connection details for the database:
Host: localhost, User: root, Password: password123, Database: company_db
Table structure is as follows:
Field Type
employee_id varchar(5)
employee_name varchar(100)
department varchar(50)

import mysql.connector

def emp_dept(d_name):
connection = mysql.connector.connect(
host='localhost',
user='root',
passwd='password123',
database='company_db'
)
cursor = connection.cursor()
query = """SELECT employee_id, employee_name, department
FROM employees
WHERE department = '{}'""".format(d_name)
cursor.execute(query)
results = cursor.fetchall()
if results:
print("Employees in the",d_name, "department:")
for row in results:
print(row)
else:
print("No employee found in the",d_name,"deptartment")
cursor.close()
connection.close()

department = input("Enter the department name: ")


emp_dt(department)
Output:
Employees in the 'HR' department:
(1, 'Alice', 'HR')

4. Write a Python program to connect to a MySQL database and fetch details of all
students enrolled in a specific course provided by the user.
Use the following connection details:
Host: localhost, User: root, Password: password123, Database: school_db
The table students has the following schema:
Field Type
student_id varchar(4)
student_name varchar(60)
course varchar(40)

import mysql.connector

def get_students(course):
conn = mysql.connector.connect(
host='localhost',
user='root',
passwd='password123',
database='school_db'
)
cur = conn.cursor()
query = """ SELECT student_id, student_name, course
FROM students
WHERE course = '{}' """.format(course)
cur.execute(query)
res = cur.fetchall()
if res:
print("Students in the",course,"course:")
for row in res:
print(row)
else:
print("No students found in the",course,’course")
cur.close()
conn.close()

course = input("Enter the course name: ")


get_students(course)

Output:
Students in the 'Mathematics' course:
(1, 'Alice', 'Mathematics')
(3, 'Charlie', 'Mathematics')

You might also like