0% found this document useful (0 votes)
4 views

Python Interface with MySQL

This document outlines the steps to connect Python with a MySQL database using the mysql.connector package. It explains the creation of connection and cursor objects, executing SQL queries, fetching records from result sets, and formatting query strings. Additionally, it emphasizes the importance of the commit() method for making changes permanent in the database.

Uploaded by

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

Python Interface with MySQL

This document outlines the steps to connect Python with a MySQL database using the mysql.connector package. It explains the creation of connection and cursor objects, executing SQL queries, fetching records from result sets, and formatting query strings. Additionally, it emphasizes the importance of the commit() method for making changes permanent in the database.

Uploaded by

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

INTERFACE PYTHON WITH MYSQL

The steps to connect to a database from within a Python application are as follows:
Step 1: Start Python.
Step 2: Import the packages required for database programming. (Create a connection object)
Step 3: Open a connection to the database
Step 4: Create a cursor object.
Step 5: Execute a query.
Step 6: Extract data from result set.
Step 7: Clean up the environment.

What is the package used for creating a Python database connectivity application?
mysql.connector is the package used for creating a Python database connectivity application.
After importing mysql.connector, a database connection is established using the connect()
method.
What is a connection object?
A connection (database connection object) controls the connection to the database. It
represents a unique session with a database connected from within a script/program.
The cursor() method creates a cursor from within Python.
What is a cursor object?
A database cursor is a special control structure that facilitates the row by row processing of
records in the resultset, i.e., the set of records selected as per query.

Which function/method do you use for executing an SQL query?


The execute() function with cursor object is used for executing an SQL query.
The running of sql query through database cursor results into the selected records returned in
the form of resultset.

What is a resultset?
The resultset refers to a logical set of records that are fetched from the database by executing
an SQL query and made available to the application program.
Which method do you use to fetch records from the result set ?
The fetchall() method, fetchmany() method, or fetchone() method can be used to fetch records
from the result set.

The fetchall() method will return all the rows from the resultset in the form of a list containing
the records.
It returns a list of tuples. (An empty list if there are no records to fetch)
The fetchone() method will return only one row from the resultset in the form of a tuple
containing a record.
It returns a tuple. (None if there are no records to fetch)
The fetchmany(n) method will return only the n number of rows from the resultset in the form
of a list containing the records.
It returns a list of tuples. (An empty list if there are no records to fetch)
The default value of n is 1. fetchmany() without a parameter would return a list with a single
tuple in it
If n is greater than the number of available records, it fetches the available records (Doesn’t give
an error)
The rowcount returns how many rows have been fetched so far using various fetch methods.
rowcount is NOT a function. it is a value

Formatting Query Strings using %s


“%” is the original syntax for formatting strings in Python. We use %s as the placeholder for a
variable in the string literal and provide the variable after the string using % tuple_ofvalues.
e.g. 1
job= input(“Enter job to search”)
que= ”SELECT * FROM Emp WHERE Job=’%s’ ” %(job,)
cur.execute(que)
Here %s will be replaced by the value in the tuple. (Remember to put quotes ‘%s’ wherever
string is required)
e.g. 2
cls=int(input(“Enter class to search”))
sec=int(input(“Enter section to search”))
que= “SELECT Admno, Name FROM Student WHERE Class=%s AND Sec=’%s’ ”%(cls, sec)
cur.execute(que)

Formatting Query Strings using {} and format() function


This is a new style used in Python later versions.
Here we use {} as placeholders in our string literal, then call the format() method passing in
expressions. The format() method returns a formatted version of the string substituting the
placeholders with the values of its arguments.

e.g. 1
job=input(“Enter job to search”)
que=”SELECT * FROM Emp WHERE Job=’{}’ ”.format(job)
cur.execute(que)
Here {} will be replaced by the argument of the format method. (Remember to put quotes ‘{}’
wherever string is required)

e.g. 2
cls=int(input(“Enter class to search”))
sec=int(input(“Enter section to search”))
que= “SELECT Admno, Name FROM Student WHERE Class={} AND Sec=’{}’ ”.format(cls, sec)
cur.execute(que)

commit() method is used to permanently make the changes made in the database when
working with database connections in Python.
The execution of INSERT, DELETE and UPDATE commands should be followed by the commit()
statement. Only then will the changes be made permanent.
e.g.
que= “INSERT INTO Student VALUES(5678, ‘Kate’, 12, ‘K’, NULL)”
cur.execute(que)
con.commit()

You might also like