RCS classes
Interface PYTHON with MySQL notes
Introduction
➢ When you design real life applications, you are bound to
encounter situations wherein you need to manipulate data
stored in a database through an application designed by
you.
➢ In order to connect to a database from within the Python,
you need a library that provides connectivity functionality.
There are so many libraries, but we will use MySQL
connectivity library.
Installing MySQL Connector
➢ In cmd ptomt write:- pip install mysql-connector
➢ After installing open python shell and write:-
➢ If it doesn’t show any error, then you have installed it
successfully.
Open a connection to a Database
Example:-
➢ To check the current user and host of the system, type:-
Create a Cursor instance
A database cursor is a special control structure that facilitates
the row by row processing of records in the result set, i.e. set of
records retrieved as per query.
Execute a Query
Once you have created a cursor, you can execute SQL queries
using execute() function with cursor object.
Example:-
Extract data
Extract data from Resultset
➢ Data=[Link]():- Return all the records retrieved
as per query in a tuple form.
➢ Data=[Link]():- It will return one record from
the resultset as a tuple. First time, it will fetch first record,
next time it will fetch the second record.
➢ Data=[Link](n):- It fetches n records in the
form of a tuple. By default n = 1.
➢ Variable=[Link]:- This property of cursor
returns the number of rows retrieved.
Parameterized Query
➢ Old Style: String template with % formatting f%v
Where, f is a template string, v specifies the values to be
formatted using the template. v must be a tuple.
Output
➢ New Style: String template with % formatting.
Output
INSERT Command
DELETE Command
UPDATE Command
Multiple values Insertion