You are on page 1of 8

Python- MySQL

Connectivity
WHAT IS A DATABASE?
A database is basically a collection of structured data in such a way that it can
easily be retrieved, managed and accessed in various ways. One of the simplest
forms of databases is a text database. Relational databases are the most popular
database system which includes the following:
• MySQL
• Oracle Database
• SQL server
• Sybase
• Informix
• IBM db2
• NO SQL

MySQL
SQL (Structured Query Language) is
a standard language for relational
databases that allow users to do
various operations on data like,
Manipulating, Creating, Dropping,
etc. it supports tools for avoiding
redundant data and ensures integrity
of data. Python supports DDL (Data
Definition Language) and DML (Data
Manipulation Language) and Query
processing. For database
programming, the Python DB-API is
the commonly used module that
provides a database application
programming interface.

2
Python-MySQL An application stores a large amount of data in the for
which is not directly visible/accessible by the user. Thi
Connectivity to give suitable responses, retrieving information etc. t
called Back-End Database
For designing real life applications, we
need to store information or data to the SQL Commands like create, update, alter, insert, delet
memory. For usual example programs we DDL Commands can be implemented using the python
accept data from the user process it and
display some output. But these data are
Why Python?
not stored, thus when we run the
program again, we need a new set of There are several advantages are there for integrating
data. This drawback can be overcome by Python is:
integrating python interface with a • Efficient and Faster
database. Thereby fetching the data • Portable
whenever necessary. • Platform-Independent
• Support for SQL Cursors
• Connection Management
Front End & Back End • Support for RDBMS
The input data is fetched/captured from • Compatibility with Multiple database systems
the user using the python interface. Thus,
in a database programming application
python is the Front-End Interface of
the application

3
Installing MySQL-Connector
To establish connectivity between python and MySQL, Python Database
Interfaces and API (Application Programming Interface) s.
A Database API process includes
• Importing API Module
• Establishing connection with a database
• Performing SQL Statements
• Closing Connection

Connecting with Python


• Install MySQL-connector using the ‘pip’ command in the command
prompt
(connector must be installed in the same directory of python)
• Once directory is selector install using the following command

python-m pip install mysql-connector

• After installation type import mysql-connector in the shell window, if


no error message is displayed, then installation and connection is
done and you can start Database programming.

Establishing Connection
To establish connection between MySQL dB and Python as the first step we
have to import the mysql.connector module. in this step we are importing
the installed mysql connector to python script.
import mysql.connector

In the second step we have to create a connection object using a username


as root and a password that set during server installation through the
Localhost.
Con.obj=mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpaswrd")

Cursor Object
As the third step, to use the connection created there must have to be a
cursor object. It allows us to operate in multiple environments using a single
connection.
Cursors are created by the connection.cursor() method. Once the cursor is
created it lasts till the session is wrapped.
4
Establishing Connection
1. Use the mysql.connector.connect() method to create the
connection object with the required parameters (host, user, paswrd).
mydb=mysql.connector.connect(host=’*’,user=’*’,passwd=’*’)
2. Use the connection object to create the cursor object
mycursor=mydb.cursor()
3. Use cursor.execute() to execute MySQL queries.
mycursor.execute(“SELECT * FROM SCHOOL”)
4. After work use connection.close() to close the connection with
MySQL.
5. Use Exception to catch if any arise during the program.

Connection Arguments
• Username: Username of MySQL server. Default value is “root”.
• Password: given during the time of installation. If user is root
password is not necessary.
• Hostname: Server name or IP address of the system.

Implementation of MySQL Queries


Before connecting to a MySQL database, make sure of the followings:
• You have created a database.
• You have created a table in created Database.
• This table has necessary fields.
• User ID and password are set to access the Database.
• Python module MySQLdb is installed properly on your machine.

5
Python MYSQL Database Connection

import.mysql.connector: This line import the MYSQL Connector in to


the program. In case the connection fails, import error will be displayed.
For example: ER_ACCESS_DENIED_ERROR when username or password
is wrong

mysql.connector.connect(): this function is used to connect MySQL


Database, which accepts required parameters Host, Database, User and
Password.

connect(): this function establishes connection to the MySQL database


from Python application and returns a MySQL Connection object. Using this
Connection object, we can perform various operations on the database.
If any of the parameters of the connect method is wrong or missing an
exception is raised. For example, wrong username.

conn.is_connected(): to verify if our Python application is connected to


MySQL successfully.

connection.cursor(): This method returns a cursor object. Using which,


we can execute SQL queries. Cursor objects interact with the MySQL
server using the connector object.

cursor().execute(): we can execute SQL queries in a python program


using the execute() method along with the cursor object.

After executing each query, we can further check or verify the command
have been executed or not using the MySQL command prompt using the
SQL queries.

6
Implementing DDL Commands
Using the important DDL commands we can modify the already created
table, insert data into the table etc. the python script.
Example:

Methods to manage MySQL Transactions


Python-MySQL connector has the following methods to facilitate database
transactions;
commit: mysql.connection.commit() method commits the current
transaction with the MySQL server.
Syntax: connection.commit()
rollback: mysql.connection.rollback() reverts or undo the changes
made in the current transaction.
Syntax: connection.rollback()
autocommit: to enable or disable the auto-commit feature

Fetching Data From The Table


Fetching useful information from the database is also known as READ
operation. For fetching/Read operation 3 methods are used;
 fetchone(): to fetch one record, it returns next row of a query
result
 fetchall(): to fetch multiple values, it fetches all the records that
have not already selected.
 rowcount(): read-only attribute returns the count of the rows
affected by the execute() command.

7
Inserting and Deleting Data
Insertion of data to a table is done with the command INSERT INTO, and
deleting rows from a table is done using the DELETE FROM <table_name>.
Similarly UPDATE command is used to update one or more records on the
table.
Closing the connection
A database can only handle a limited number of connections at a time. To
close a connection that established using the connector object
cursor.close() method is used. It is ideal to close the connection after
finishing the operations on the database.

You might also like