Xii - Python With SQL
Xii - Python With SQL
Xii - Python With SQL
MySQL
CONNECTING TO MYSQL FROM
PYTHON
• MySQL.connector should be installed
• After Installing this you have to include this
Library in your Python code.
• You can also use pymysql Library which is
purely provided by Python for connecting with
MySQL whereas MySQL.connector is provided
by Oracle which owns MySQL.
Steps for Creating Database
Connectivity Applications
• Step 1 : Start Python
• Step 2 : Import the packages required for
database programming.
• Step 3 : Open a connection to database.
• Step 4 : Create a cursor instance.
• Step 5 : Execute a query.
• Step 6 : Extract data from result set.
• Step 7 : Clean up the environment.
• You can write –
import mysql.connector
or
import mysql.connector as sql
To include the package before starting connection. The 2nd
method can be used to provide a short name for package.
mycon=sql.connect(host=“localhost”,user=“root”,passwd
=“MyPass”,database=“GNHSS”)
• After Connecting we have to create a CURSOR
instance.
• A Database Cursor is a special control structure that
facilitates the row by row processing of records in
the resultset i.e. the set of records retrieved as per
query.
cursor=mycon.cursor()
• SQL query can be executed by –
cursor.execute(“SELECT * FROM data”)
• The above code will execute the query and store
the resultset in a cursor object, which can be
extracted using any one of the following functions -
1. fetchall() – It will return all the records retrieved
as query in a tuple form
2. fetchone() – It will return one record at a time.
3. fetchmany(n) – It will return required no. of rows
from the resultset.
4. cursor.rowcount – is a property of cursor object
that returns the number of rows retrieved from the
cursor so far.
SAMPLE PROGRAM TO SHOW CONNECTION WITH
MYSQL –
Q. Program to display Records from table :-
import mysql.connector as sql
mycon=sql.connect(host="localhost",user="root",passwd="Giri9
753@@",database="gnhss")
if mycon.is_connected() :
print("CONNECTED")
cursor=mycon.cursor()
cursor.execute("SELECT * FROM STUDENT")
data=cursor.fetchall()
for row in data :
print(row)
mycon.close()