0% found this document useful (0 votes)
3 views7 pages

MySQL Connectivity with Python

The document provides a comprehensive guide on MySQL connectivity with Python, detailing how to create connection and cursor objects, execute SQL commands, and manage transactions using commit and rollback functions. It explains various methods for fetching data from tables, including fetchone, fetchmany, and fetchall, as well as the use of parameterized queries for dynamic inputs. Additionally, it includes practice problems to reinforce the concepts covered, such as displaying records and updating or deleting entries in a database.

Uploaded by

abheeraajsingh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views7 pages

MySQL Connectivity with Python

The document provides a comprehensive guide on MySQL connectivity with Python, detailing how to create connection and cursor objects, execute SQL commands, and manage transactions using commit and rollback functions. It explains various methods for fetching data from tables, including fetchone, fetchmany, and fetchall, as well as the use of parameterized queries for dynamic inputs. Additionally, it includes practice problems to reinforce the concepts covered, such as displaying records and updating or deleting entries in a database.

Uploaded by

abheeraajsingh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 7

MySQL Connectivity with Python

CREATING CONNECTION OBJECT

CREATING CURSOR OBJECT

CREATING A TABLE

Inside the .execute() – you just put the normal MySQL query that you would use while
working in MySQL as it is
SHOWING TABLES

OUTPUT

Whenever you’re trying to extract/fetch data from a record, you need to use loop in order
to iterate through the cursor object and print the data stored in it
But you don’t need to use any loops while creating, modifying, adding items, in a relation
(table)
ROWCOUNT attribute:
rowcount attribute gives you the total number of records inserted in the table after the
execution of the command

COMMIT() function:
commit function sends a COMMIT statement to MySQL server which commits
(confirms/locks) the current transaction (insertion/modification of data)
e.g. conobj.commit()

ROLLBACK() function:
reverts the changes made by the current transaction
e.g. conobj.rollback()

AUTOCOMMIT function:
it’s a method to set a value either True or False, which if set to true, auto-commits all the
transaction made

CLOSING CURSOR AND CONNECTION:


After a program is finished you must ‘close’ the cursor_object and the connection_object
like so,

Always close the cursor_object first and then the connection_object


READ OPERATIONS
• Fetchone(): fetches one row/record from the table and stores it in a tuple or a list.
Executing fetchone() for the first time will print the first record, executing it 2nd time
will display the second record and so on, till no more records are left, then it prints
None.
• Fetchmany(n): fetchmany as the name suggests, fetches the number of records
that are passed to it as an argument in the form of a list of tuples i.e. n. suppose
you execute,

It will print the first 3 records of the table - [(Vaibhav, xii a),(Aliza, xii a),]

• Fetchall(): fetchall, prints all the records that are there in the relation/table. This
also returns a list of tuples. If some rows are already retrieved, using fetchone or
fetchmany, then fetchall returns remaining rows.
Whenever you use any of these commands you need to store it in a variable and then to
print the data, you have to iterate through the variable (basically using a loop, mostly
‘for’)

DISPLAYING RECORDS ALONG WITH NUMBER OF RECORDS


Here the records are getting printed in the form a tuple, we can also print the data in
normal text form in the following way:

PARAMETERISED QUERY
Parameterized query is used when you want to deal with dynamic variable while
executing a MySQL command using python. Suppose you want to add the details of a
student in a given table, but the user inputs the value that he wants to add, now in this
case in order to make the program dynamic (usable for any values entered by the user)
we have to use parameterized queries
• Concatentation: only useful when you have the dynamic variable at the end of the
MySQL query.

where ‘rno’ is a dynamic user defined variable (using input statement)

• String template using %s formatting: useful when multiple variables are dynamic

Now here, whenever you want a dynamic variable, you put % sign and ‘s’ after it, then
after the query, you write %(parameter,parameter), where these parameters are the
dynamic variable that you want to use in the query. Note that the order is important,
meaning the first parameter that you put in %(parameter,parameter) will get linked to
the first ‘%s’ in the query.
Therefore specifically in this example, I have 2 dynamic variables, ‘rno’ and ‘nm’ which
are assigned some certain value. When I put %(nm, rno), nm gets assigned to the first
‘%s’ in the query and rno gets assigned to the second ‘%s’ in the query. Therefore the
resultant query becomes:

OUTPUT

There’s another way to use ‘%s’ function as depicted below:

• String template using {} and format: This is also used when there are multiple
dynamic variables involved

This is very similar to %s, only difference is, in place of ‘%s’ you have these curly braces
and in place of %(p1,p2), you have ___ .format(p1,p2,p3,p4) ___ (p = parameter). The
parameters in this formatting are also ordered, meaning p1 will get linked to the first
curly brace, p2 with the second curly brace and so on.
NOTE: You will require to put inverted comma around {} when dealing with string or
date data-type otherwise an error will be raised.
DELETING RECORDS FROM A TABLE
As ‘delete’ is a DML command (data manipulation language) the transaction needs to
be commited therefore, it’s important to use connection_object.commit()

OUTPUT

VERIFCATION

PRACTICE PROBLEM: display the above inserted data

PRACTICE PROBLEM: write a code from scratch to display the first 3 records from the
table ‘student’ in the database ‘school’

PRACTICE PROBLEM: taking input from the user to input the roll_no to update the marks
of the student associated with that roll_no [DON’T FORGET TO USE commit()]

TABLE STRUCTURE:
HINTS:
• Make the connection and cursor object
• Input roll_no from user
• Fetch detail of the inputted roll no
• If no such record found, print “no record(s) found”
• Otherwise, display the found record
• Take input of new marks from the user
• update the detail of that inputted roll no
• Recommended to use {} and format function

PRACTICE PROBLEM: WAP to delete the record of a student on the basis of name
fetched from the user at run-time [DON’T FORGET TO USE commit()] [use either %s or
string formatting {}]

You might also like