Interface Python With MySQL-1
Interface Python With MySQL-1
For designing a real life project, you need to store the data either in form of files or in
database. As DBMS gives more options and flexibility to work on data, so it is preferred
over normal data files. The Python standard for database interfaces is the Python DB-
API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a
wide range of database servers. We will be using MySQL Connector Library to connect
to database.
On Unix and Unix-like systems, Python generally located in a directory included in the
default PATH setting.
On Windows, If Python doesn’t exist in the system’s PATH, please manually add the
directory containing python.exe yourself.
Right click on My Computer icon, click on Properties, then Advanced system settings
and Environment variables. Without deleting anything add <pythonpath>. If you have
Python.exe file in path in “C:\Python37-64\python.exe” then add the same to path
variable.
There are multiple ways to install Oracle’s MySQL Connector Python on your machine. The
following are a few ways.
You should get the following messages after running pip command: –
Collecting mysql-connector-python…….
Downloading packages……….
Example,
Output:
You can create Cursor object using the cursor() method of the Connection object/class.
Syntax:
<cursor_object>= connection_object.cursor()
#Creating a cursor object using the cursor() method
cursor = db_connection.cursor()
Properties
Following are the properties of the Cursor class –
Sr.No Property & Description
1 column_names
This is a read only property which returns the list containing the column names of a result-set.
2 description
This is a read only property which returns the list containing the description of columns in a
result-set.
3 lastrowid
This is a read only property, if there are any auto-incremented columns in the table, this returns
the value generated for that column in the last INSERT or, UPDATE operation.
4 rowcount
This returns the number of rows returned/updated in case of SELECT and UPDATE
operations.
5 statement
This property returns the last executed statement.
Now let’s write a complete script to create connection object and cursor object, put and
execute queries to create a database and list all the databases available by extracting data
from the resultset.