SQL-Connectivity
SQL-Connectivity
SQL-Connectivity
MYSQL
Connecting Python application with MySQL
Introduction
Every application required data to be stored for future
reference to manipulate data. Today every application stores
data in database for this purpose.
For example, reservation system stores passengers details for
reserving the seats and later on for sending some messages or
for printing tickets etc.
In school student details are saved for many reasons like
attendance, fee collections, exams, report card etc.
Python allows us to connect all types of database like Oracle,
SQLServer, MySQL .
In our syllabus we have to understand how to connect Python
programs with MySQL
Pre-requisite to connect Python with
MySQL
Before we connect python program with any database like
MySQL we need to build a bridge to connect Python and
MySQL.
To build this bridge so that data can travel both ways we need
a connector called “mysql.connector”.
We can install “mysql.connector” by using following
methods:
At command prompt (Administrator login)
◼ Type “pip install mysql.connector” and press enter
◼ (internet connection is required)
◼ Thisconnector will work only for MySQL 5.7.3 or later
Or open
“https://dev.mysql.com/downloads/connector/python/”
and download connector as per OS and Python version.
Connecting to MySQL from Python
Or
import mysql.connector as ms
Cursor_name.execute(query)
For e.g.
Output shows cursor is created and query is fired and stored, but no data is coming. To
fetch data we have to usefunctions like fetchall( ), fetchone( ), fetchmany( ) are used.
Mysql connector
mysql.connector as mys
mys
Fetchall( ) – method extracts all rows
INSERTING RECORDS
Inserting data in MySQL table
from Python
INSERT and UPDATE operation are executed in the
same way we execute SELECT query using execute( ) but
one thing to remember, after executing DML Commands -
insert or update or delete query we must commit our
query using connection object with commit( ).
For e.g. (if our connection object name is mycon)
mycon.commit( )
BEFORE PROGRAM EXECUTION