0% found this document useful (0 votes)
17 views4 pages

Python MySQL Database Operations Guide

The document provides Python code examples for connecting to MySQL databases and performing various operations such as inserting, updating, and retrieving records from different tables. It includes specific functions for adding and displaying items in a STATIONERY table, displaying flight details from a FLIGHT table, updating quantities in a SHOP table, and inserting and displaying records in a STUDENT table. The document outlines the necessary database connection parameters for each operation.

Uploaded by

iitianarshad95
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views4 pages

Python MySQL Database Operations Guide

The document provides Python code examples for connecting to MySQL databases and performing various operations such as inserting, updating, and retrieving records from different tables. It includes specific functions for adding and displaying items in a STATIONERY table, displaying flight details from a FLIGHT table, updating quantities in a SHOP table, and inserting and displaying records in a STUDENT table. The document outlines the necessary database connection parameters for each operation.

Uploaded by

iitianarshad95
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON – MYSQL CONNECTIVITY

NOTES:
Connection to database :
if mycon.is_connected():
print(“Successfully connected”)
Parameterised Queries
 “INSERT INTO EMP VALUES({}, “{}”, {});”.format(empid, name, salary)
 “INSERT INTO EMP VALUES(%s %s %s ) %(empid, name, salary)”
o If only one value, use comma inside tuple. Eg: (empid,)
 “SELECT * FROM EMP WHERE empid=” + str(empid)
 To count the number of records present in the resultset: [Link]

1. 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 table STATIONERY. 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
import [Link] as m
def Addanddisplay():
mycon=[Link](host=”localhost”, user=”root”, password=”Pencil”, database=”ITEMDB”)
mycur=[Link]()
itemno=int(input(“Enter item No:”))
itemname=input(“Enter item name”)
price=float(input(“Enter price:”))
qty=int(input(“Enter quantity:”))
query=”INSERT INTO STATIONERY VALUES ( {},”{}”,{},{} );”.format(itemno,itemname,price,qty)
[Link](query)
[Link]()
[Link](“SELECT * FROM STATIONERY WHERE PRICE > 120;”)
record=[Link]()
for rec in record:
print(rec)
[Link]()
2. Sumit wants to write a code in python to display all the details of the passengers from the from the table
flight in MySQL database, Travel. The table contains the following attributes:
F_code: Flight code (string)
F_name: Name of the flight (string)
Source: Departure city of flight (String)
Destination: Destination of city (String)
Consider the following to establish connectivity between Python and MySQL.
Username: root
Password: airplane
Host:localhost
import [Link] as m
mycon=[Link](host=”localhost”, user=”root”, password=”airplane”, database=”Travel”)
mycur=[Link]()
query=”SELECT * FROM FLIGHT;”
[Link](query)
record=[Link]()
for rec in record:
print(rec)
[Link]()
3. Sunil wants to write a program in python to update the quantity to 20 of the records whose item code is 111
in the table named shop in MySQL database named Keeper.
The table shop in MySQL contains the following attributes:
 Item_code: Item code(integer)
 Item_name: Name of the item(String)
 Qty: Quantity of the item(Integer)
 Price: Price of the item(Integer)
Consider the following to establish connectivity between Python and MySQL.
 Username: admin
 Password: Shopping
 Host: localhost
import [Link] as m
mycon=[Link](host=”localhost”, user=”admin”, password=”Shopping”, database=”Keeper”)
mycur=[Link]()
query=”UPDATE SHOP SET QTY=20 WHERE ITEM_CODE=111;”
[Link](query)
[Link]()
[Link]()
4. Kabir wants to write a program in Python to insert the following record in the table named Student in
MYSQL database, SCHOOL:
 rno(Roll number )- integer
 name(Name) - string
 DOB (Date of birth) – Date
 Fee – float
Note the following to establish connectivity between Python and MySQL:
 Username - root
 Password - tiger
 Host - localhost
The values of fields rno, name, DOB and fee has to be accepted from the user. Help Kabir to write the program
in Python.

5. Sartaj has created a table named Student in MYSQL database, SCHOOL:


 rno(Roll number )- integer
 name(Name) - string
 DOB (Date of birth) – Date
 Fee – float
Note the following to establish connectivity between Python and MySQL:
 Username - root
 Password - tiger
 Host - localhost
Sartaj, now wants to display the records of students whose fee is more than 5000. Help Sartaj to write the
program in Python.

Common questions

Powered by AI

To connect to a MySQL database using Python, you typically follow these steps: 1) Import the mysql.connector module, 2) Establish a connection using connect() by providing the host, user, and password, 3) Create a cursor object to interact with the database, and 4) Execute SQL queries using the cursor. Common credentials used are the host ('localhost'), user ('root' or 'admin'), and the password specific to each user ('Pencil', 'airplane', 'Shopping', 'tiger').

Security best practices in Python-MySQL connectivity include using parameterized queries to prevent SQL injection, employing secure authentication with strong passwords, and encrypting sensitive data in transit using SSL/TLS connections. Regularly updating the MySQL server and Python libraries to the latest secure versions, implementing least privilege access by limiting database user permissions, and logging database activity to monitor suspicious actions are critical. Ensuring these practices protects the integrity and confidentiality of sensitive data .

Closing database connections is crucial to free up database resources, avoid locking tables or data, and prevent the application from reaching the maximum connection limits. Failing to close connections can lead to memory leaks and degraded performance over time. This practice is seen in all provided program examples, where connections are closed using mycon.close() after executing MySQL queries .

To dynamically update item quantities based on conditions in another table using Python, you would first execute a SELECT query to fetch conditions from one table, then iterate over the results to update the target table with an UPDATE statement. Use parameterized queries to insert retrieved condition values into the UPDATE statement safely. Modify the program structure to use loops or conditional logic to apply updates. This approach reflects the method used to update 'Qty' in the 'shop' table when 'item_code' is 111 .

A Python function to insert and retrieve records involves establishing a database connection, using cursor objects to execute SQL commands, and committing changes. For insertion, use the INSERT INTO SQL statement. To retrieve records, apply a SELECT statement with a WHERE clause for conditions. For example, a function can insert data into a 'STATIONERY' table and retrieve records where 'Price > 120' as demonstrated in Addanddisplay().

The recommended approach for updating records in a MySQL database using Python is to use a combination of SQL UPDATE statements and parameterized queries. This is effective as it ensures data integrity and protection against SQL injection attacks by using placeholders for input values, which are then safely substituted by the database engine. For example, Sunil's program updates the 'Qty' field in the 'shop' table for a specific 'item_code' using a secure method .

Parameterized queries in Python improve security by preventing SQL injection attacks. Instead of directly concatenating and constructing SQL queries with user inputs, parameterized queries use placeholders that separate SQL logic from data input. This ensures that input is treated strictly as data and not executable code, thus mitigating the risk of an attacker injecting malicious SQL commands .

To retrieve specific records based on a criterion in a Python-MySQL query, use a SELECT statement with a WHERE clause that defines the condition. Logical operators like '=', '>', '<', '>=', '<=', and 'LIKE' can specify criteria, such as 'WHERE fee > 5000' to find students with fees exceeding this amount. Conditions ensure that only relevant records are fetched, optimizing query results .

Handling date-type data in Python for MySQL requires proper formatting consistent with the SQL DATE type. Use Python's datetime module to manage and format date entries. When inserting dates into a MySQL database, ensure they're in 'YYYY-MM-DD' format to comply with SQL standards. For example, when entering a date in the 'Student' table, validate and convert user inputs to this format to avoid errors .

To modify a Python script for handling multiple user inputs safely, use type validation and parameterized queries. First, validate each input according to its expected data type (e.g., use int() for integers, float() for floats, and specific formats for dates). Next, employ parameterized queries to insert inputs into SQL statements without directly embedding them, protecting against SQL injection. For instance, inputs for 'rno', 'name', 'DOB', and 'fee' should be validated before inserting them into a 'Student' table .

You might also like