cs12 - Python Connectivity With SQL

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Python Connectivity with SQL

 A database is nothing but an organized collection of data.


 Data is organized into rows, columns and tables and it is indexed to make it easier to find
relevant information.
 All companies whether large or small use databases. So it become necessary to develop
project/software using any programming language like python in such a manner which can
interface with such databases which support SQL.
 Form / any user interface designed in any programming language is Front End whereas
data given by database as response is known as Back-End database.
 SQL is just a query language; it is not a database.
 To perform SQL queries, we need to install any database for example Oracle, MySQL,
MongoDB, PostGres SQL, SQL Server, DB2 etc.
 Using SQL in any of the dbms ,databases and table can be created and data can be
accessed, updated and maintained.
 Python Database API supports a wide range of database servers, like msql , mysql,
postgressql, Informix, oracle, Sybase etc.

Why choose Python for database programming


• Python is more efficient and faster as compared to other programming languages.
• Portability of python programs.
• Support platform independent program development.
• Python supports SQL cursors.
• Python itself take care of open and close of connections.
• Python supports relational database systems.
• Porting of data from one DBMS to other is easily possible as it supports large range of APIs
for various databases.
• Python can be used in database applications.
• One of the most popular databases is MySQL.
What is PIP?
 PIP is a package manager for Python packages, or modules.
 Pip is one of the most famous and widely used package management system to install and
manage software packages written in Python and found in Python Package Index (PyPI).
 Pip is a recursive acronym that can stand for either "Pip Installs Packages" or "Pip Installs
Python". Alternatively, pip stands for "preferred installer program".

Note: If you have Python version 3.4 or later, PIP is included by default.

PYTHON INTERFACE WITH SQL DATABASE


Here we are using mysql as backend database because of it is open source, free and portable and
widely used.
Any one of mysql-connector or MySQLdb can be used for database programming.

1. mysql-connector
MySQL-Connector enables Python programs to access MySQL databases, using an API that is
compliant with the Python Database API Specification v2.0 (PEP 249). It is written in pure Python
and does not have any dependencies except for the Python Standard Library.

Install MySQL Driver


• Python needs a MySQL driver to access the MySQL database.
• Use PIP to install "MySQL Connector".
• PIP is most likely already installed in your Python environment.
• Navigate your command line to the location of PIP, and type the following:
Download and install "MySQL Connector":

Now you have downloaded and installed a MySQL driver.

Test MySQL Connector


To test if the installation was successful, or if you already have "MySQL Connector" installed, type
the following content on python shell:

It executes successfully, producing no error, signifies that mysql connector is successfully


installed.

ESTABLISHING CONNECTION BETWEEN PYTHON AND MYSQL


STEP 1 : Create Connection
• After completing the first step of installation of mysql connector, the next step is to use
mysql in python scripts.
• For this, we need to make a connection to the database that we wish to use.
• Use the username and password from your MySQL database. (Note it during installation.
Default username is root and password is tiger )
• connect () is used to establish a connection to the database. It returns a
MySQLConnection object.
This function accepts 4 parameters :
1) host name : This is the server name or IP address of the machine on which MySQL
is running. It is the place where database is located. If we are running localhost, then
we can use the value of this parameter as localhost or its IP i.e. 127.0.0.0
2) username : Username is the name we use to work with mysql. Default username for
mysql is root.
3) passwd / passwrd : It is given by the user at the time of installing mysql database.
Default password is tiger.
4) Database name : It is the name of the database to which we want to connect.

STEP 2 : Create Cursor Object


• The next step for interacting with mysql through python is to create the cursor object.
• It will let us execute all the queries we need.
• We need to create object of class cursor that allows python code to execute commands
using execute() method.

STEP 3 : Execute commands


• Use the cursor object created in previous step to execute SQL queries from python.

STEP 4 : Close the cursor object


In the last step, we need to close the cursor object and the MySQL database connection.

CONNECTION OBJECT’S METHODS


1. close() : This method sends the quit message and closes the database connection to
give up resources.
2. commit() : The execution of COMMIT statement makes all the modification made by the
current transaction become permanent. Note that if the database supports an auto-commit
feature, this must be initially off.
3. rollback() : Transaction rollback becomes necessary if an error occurs during the
execution of a transaction. Closing a connection without committing the changes first will
cause an implicit rollback to be performed.
4. cursor() : Return a new cursor object using the connection. The primary purpose of this
object is to provide SQL queries using execute() method.

CURSOR OBJECT’S METHODS


1. close() : This method, closes a cursor, exhausts all remaining data
2. execute() : It prepares and executes a database operation.
3. fetchone()
4. fetchall()
5. fetchmany()

EXAMPLE TO DEMONSTRATE ALL THE STEPS OF ESTABLISHING LINK


BETWEEN MYSQL AND PYTHON

CREATING DATABASE

CREATING TABLE IN DATABASE


INSERTING RECORDS IN TABLE

RETRIEVING RECORDS FROM SQL TABLE AND DISPLAYING IN PYTHON SHELL

MySQLCursor.fetchall() Method
The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no
more rows are available, it returns an empty list.

RETRIEVING RECORDS FROM SQL TABLE AND DISPLAYING IN PYTHON SHELL

MySQLCursor.fetchone() Method
This method retrieves the next row of a query result set and returns a single sequence, or None if
no more rows are available.
RETRIEVING RECORDS FROM SQL TABLE AND DISPLAYING IN PYTHON SHELL

MySQLCursor.fetchmany() Method
rows = cursor.fetchmany(size=1)
This method fetches the next set of rows of a query result and returns a list of tuples. If no more
rows are available, it returns an empty list.

RETRIEVING RECORDS FROM SQL TABLE AND DISPLAYING IN PYTHON SHELL

MySQLCursor.rowcount() Method
We can get number of rows affected by the execute() by using rowcount.

DELETING RECORDS FROM SQL TABLE


UPDATING RECORDS IN SQL TABLE

Managing Database Transactions


Database transaction represents a single unit of work. Any operation which modifies the state of
the MySQL database is a transaction.
Python MySQL Connector provides the following method to manage database transactions.
1. commit – MySQLConnection.commit() method sends a COMMIT statement to the MySQL
server, committing the current transaction.
2. rollback – MySQLConnection.rollback revert the changes made by the current transaction.
3. autoCommit – MySQLConnection.autocommit value can be assigned as True or False to
enable or disable the auto-commit feature of MySQL. By default its value is False.
Retrieving data from table on the basis of value entered by the user at run-time

Inserting record in table with the values entered by the user at run-time

You might also like