CHAPTER- 14
INTERFACE PYTHON WITH SQL
14.1 Introduction
MySQL is an open-source relational database management system (RDBMS) commonly used
for managing data efficiently.
Python offers robust libraries, such as pymysql, for integrating with MySQL to perform
operations on databases.
Database connectivity allows Python programs to interact with databases, enabling data to
be stored, retrieved, modified, and managed efficiently.
Python-to-MySQL integration is useful in real-world applications like web development, data
analysis, and automation tasks.
14.2 Connecting to MySQL from Python
To connect Python with MySQL, pymysql library is widely used, as it provides simple ways to
connect, perform queries, and handle data.
14.2.1 Steps for Creating Database Connectivity Applications
1. Install the pymysql library:
o Install the pymysql library using pip:
pip install pymysql
2. Import pymysql module in Python:
o Importing the module is necessary to access MySQL database functions.
import pymysql
3. Establish a connection to the MySQL server:
o Use pymysql.connect() function to create a connection to MySQL by specifying:
host: MySQL server address (e.g., 'localhost' if on the same machine).
user: MySQL username.
password: MySQL password.
database: Name of the specific database to connect with.
o Example:
connection = pymysql.connect(
host="localhost",
user="root",
password="your_password",
database="your_database"
o This function returns a connection object if the connection is successful.
4. Create a cursor object:
o A cursor is used to execute SQL queries on the MySQL database.
o A cursor object is created using connection.cursor().
cursor = connection.cursor()
5. Execute SQL queries:
o Use the cursor object to execute SQL queries using cursor.execute(query).
o For example, to fetch data:
cursor.execute("SELECT * FROM table_name")
6. Process the results:
o If the query returns data, use methods like fetchone(), fetchall() to retrieve data from
the result set.
7. Close the cursor and connection:
o After finishing operations, close the cursor and connection using cursor.close() and
connection.close().
o This step is crucial for releasing resources.
14.2.2 Connecting with MySQL Database using pymysql
Example Code for Connecting and Executing a Query:
import pymysql
# Establish connection
connection = pymysql.connect(
host="localhost",
user="root",
password="your_password",
database="your_database"
# Create a cursor object
cursor = connection.cursor()
# Execute a sample query
cursor.execute("SELECT * FROM employees")
# Fetch and print data
for row in cursor.fetchall():
print(row)
# Close cursor and connection
cursor.close()
connection.close()
Error Handling:
o Use try-except blocks to catch connection errors.
o Common exceptions include pymysql.MySQLError.
14.3 Parameterized Queries
Parameterized Queries prevent SQL injection by using placeholders instead of direct values
in SQL statements.
This approach secures the query by separating SQL logic from data.
Use %s as placeholders for parameters in the query.
o Example of a parameterized SELECT query:
query = "SELECT * FROM employees WHERE department = %s"
cursor.execute(query, ("Sales",))
Benefits:
o Protects against SQL injection attacks.
o Simplifies handling user-provided data in queries.
14.4 Performing Insert and Update Queries
Inserting and updating data in MySQL using pymysql is straightforward with INSERT and
UPDATE statements.
Insert Query:
o Used to add new records to a table.
o Example of an insert query:
query = "INSERT INTO employees (name, department, salary) VALUES (%s, %s, %s)"
cursor.execute(query, ("John Doe", "Sales", 50000))
connection.commit() # Save changes
o The commit() method is crucial for saving changes made by INSERT, UPDATE, or
DELETE queries.
Update Query:
o Used to modify existing records.
o Example of an update query:
query = "UPDATE employees SET salary = %s WHERE name = %s"
cursor.execute(query, (55000, "John Doe"))
connection.commit() # Save changes
o Using parameterized queries here also protects against SQL injection.
Error Handling in Insert/Update Queries:
o Include try-except blocks to handle errors, ensuring rollback() if an error occurs, to
undo uncommitted changes.
Close the connection properly:
o Closing the cursor and connection helps prevent database lock issues and resource
overuse.