Chapter 14 Interface Python With Mysql
Chapter 14 Interface Python With Mysql
Chapter 14 Interface Python With Mysql
In order to connect to a database from within Python, we typically use a library such as mysql-connector-
python or PyMySQL. These libraries provide the functionality to connect to a MySQL database, execute SQL
queries, and retrieve data. We will work with mysql connector library for the same in this chapter.
CONNECTING TO MYSQL FROM PYTHON
In order to connect Python with MySQL, we first need to install the mysql-connector-python library. Use
the following command to install the library.
import mysql.connector
or
import mysql.connecotr as sqLtor
import mysql.connector
connection = mysql.connector.connect(
host="localhost", # The hostname or IP address of the database server
user="your_username", # Username for database authentication
password="your_password", # Password for the specified username
database="your_database" # Name of the database to connect to
)
Parameters Required
The connect() function requires four parameters which are:
Host: The address of the database server. Use “localhost” if the database is on the same machine.
User: The username to log into the database.
Password: The password corresponding to the username.
Database: The specific database you want to connect to. It is optional and If omitted, the
connection is established without selecting a default database.
Connection Object
The connect() method returns a connection object that acts as the communication link with the database.
Connection Validation
We can check for the successful connection using the function is_connected() with the connection object,
which return True, if the connection is successful and false if the connection is not successful.
if connection.is_connected():
print("Connection successful")
else:
print("Connection failed")
The cursor is a fundamental component in database programming. After establishing a connection to the
database, creating a cursor allows the Python program to interact with the database by executing SQL
queries and retrieving data. Here is how it works.
cursor = connection.cursor()
Here:
The above code will execute the given SQL query and store the retrieved records (i.e., the resultset) in the
cursor object (namely cursor) which you can then use in your programs/scripts as required.
#6. EXTRACT DATA FROM RESULTSET
After executing a query (especially a SELECT query), the database returns a result set. This step focuses on
extracting and processing the data retrieved from the database using various cursor methods.
Result Set
fetchone(): Fetches a single row from the result set. If no more rows are available, it returns None.
row = cursor.fetchone()
print(row)
fetchmany(size): Fetches the specified number of rows as a list of tuples.
rows = cursor.fetchmany(3)
for row in rows:
print(row)
fetchall(): Fetches all remaining rows in the result set as a list of tuples.
rows = cursor.fetchall()
for row in rows:
print(row)
import mysql.connector
# Establish connection to the MySQL database
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="dbname"
)
# Create a cursor instance
cursor = connection.cursor()
Output
Using fetchone():
(1, 'Alice', 30, 'HR', 50000)
(2, 'Bob', 35, 'Finance', 60000)
(3, 'Carol', 28, 'IT', 55000)
(4, 'David', 40, 'Marketing', 70000)
(5, 'Emma', 25, 'Sales', 45000)
Using fetchmany() with batch size 2 :
(1, 'Alice', 30, 'HR', 50000)
(2, 'Bob', 35, 'Finance', 60000)
(3, 'Carol', 28, 'IT', 55000)
(4, 'David', 40, 'Marketing', 70000)
(5, 'Emma', 25, 'Sales', 45000)
Using fetchall():
(1, 'Alice', 30, 'HR', 50000)
(2, 'Bob', 35, 'Finance', 60000)
(3, 'Carol', 28, 'IT', 55000)
(4, 'David', 40, 'Marketing', 70000)
(5, 'Emma', 25, 'Sales', 45000)
#7. CLEAN UP THE ENVIRONMENT
After you are through all the processing, in this final step, you need to close the connection established as
follows:
connection.close()
import pymysql
Now that you have the pymysql package, the next step is to establish a connection to the MySQL database.
You need to provide the following details to connect:
host: The server where your MySQL database is running (often localhost or 127.0.0.1 for local
databases).
user: The username used to log into the MySQL database.
password: The password associated with the MySQL user.
database: The specific database you want to connect to.
connection = pymysql.connect(
)
Example Code
import pymysql
# Step 3: Open connection to the MySQL database
try:
connection = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
print("Connection successful!")
except pymysql.MySQLError as e:
print("Error while connecting to MySQL", e)
Rest of the steps, i.e., steps 4, 5, 6, 7 are identical to what you have learnt earlier in the previous section.
Note that connection object created using pymysql does not provided is_connected() method to the test
connection. Thus we shall not use it with pymysql.
PARAMETERISED QUERIES
Sometimes, we may need run queries which are based on some parameters or values that your provide
from outside, e.g.,
inp=70
SELECT * FROM student WHERE MARKS>inp;
f is a template string
v specifies the values to be formatted using the template. v must be a tuple.
“Select * from student where marks > %s” % (70,)
#2 NEW STYLE: STRING TEMPLATE WITH { } FORMATTING
In Python, new-style string formatting refers to the method introduced in Python 2.7 and Python 3.0 using
curly braces {} and the str.format() method. This method is more flexible and powerful than the old %
formatting style. It allows placeholders within the string to be replaced by values passed into the format()
method, making string formatting cleaner and more readable.
Syntax:
{}: Curly braces {} are used as placeholders for the values that will be inserted into the string.
.format(): The format() method is used to bind the placeholders to the values provided.
Example
Table Student: Structure and Data
Python code
Old Style Example
import mysql.connector
con=mysql.connector.connect(host="localhost",
password="root",
user="root",
database="school")
cur=con.cursor()
m=int(input("Enter marks:"))
s=input(“Enter stream:”)
query="Select * from student where marks>%s and stream=’%s’" % (m,s)
cur.execute(query)
data=cur.fetchall()
for i in data:
print(i)
New Style
import mysql.connector
con=mysql.connector.connect(host="localhost",
password="root",
user="root",
database="school")
cur=con.cursor()
m=int(input("Enter marks:"))
query="select * from student where marks >{} and stream = '{}'".format(m,s)
cur.execute(query)
data=cur.fetchall()
for i in data:
print(i)
import mysql.connector
con=mysql.connector.connect(host="localhost",
password="root",
user="root",
database="school")
cur=con.cursor()
r=int(input("Enter roll no:"))
n=input("Enter name:")
m=int(input("Enter marks"))
s=input("Enter stream:")
query="Insert into student values ({}, '{}', {}, '{}')".format(r,n,m,s)
cur.execute(query)
con.commit()
print(“Row inserted successfully…..”)
import mysql.connector
con=mysql.connector.connect(host="localhost",
password="root",
user="root",
database="school")
cur=con.cursor()
query="Update student set marks=50 where RollNo=3"
cur.execute(query)
con.commit()
print("Row updated successfully....")