0% found this document useful (0 votes)
5 views

pythonmysqlnew

Uploaded by

kashyapnaveen988
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

pythonmysqlnew

Uploaded by

kashyapnaveen988
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

E-SCHOOL

Topic: Interface Python with MYSQL

MYSQL with Python


Using Python Programming, we can use MYSQL database to store data. The data entered in
PYTHON gets stored in databases created in MYSQL. Python is Front-end (used to develop
User Interface) and MYSQL is used as Back-end (used to store data).

MYSQL Installer
To connect Python with MYSQL we need to install MYSQL Connector and to do so, we
need to type the following command in command prompt:
pip install mysql-connector-python

Python MySQL Database Connectivity


Import mysql.connector Package
import mysql.connector as msc

Open a Connection
connect() is used to open a connection to a MYSQL database in python.
Syntax:-
<connectionobject> = msc.connect(host=”localhost”,user=”root”,
password=”sqlpassword”, database=”databasename”)
host:- It represents IP address of database server. If database is available on local machine
then it will be “localhost” or “127.0.0.1”
user:- In mysql its default value is always “root”.
password:- is the password that was specified at time of MYSQL installation
database:- is the name of database created in MYSQL, if created.
We can use is_connected() to verify that the connection with mysql is successful.
For example:
if connectionobject.is_connected():
print(‘Successful connection’)
And then perform the remaining task only if the connection is successfully established.
“A database connection object controls the connection to the database. It represents a
unique session with a database connected from within a program/script.”
E-SCHOOL

Creating a Cursor Instance


A database cursor is a special control structure that facilitates the row by row processing of
records in the resultset. The following command is used to create cursor object:
Syntax:-
cursorinstance=connectionobject.cursor()

Executing SQL Query


Once cursor instance is created then all SQL commands can be executed using execute()
function with cursor object.
syntax:-
cusrorinstance.execute(“SQL command”)

Extract Data from ResultSet


The following functions could be used to extract data from recsultset:
cusrorinstance.fetchall()- It returns all records retrieved as per query in the form of a list of
tuples.
cusrorinstance.fetchone()- It returns one record from the resultset as a tuple.
cusrorinstance.fetchmany(n)- It returns n records from the resultset in the form of a list of
tuples.
cusrorinstance.rowcount - rowcount property of a cursor returns total number of rows
available in resultset.

Using commit()
commit() is used to save data in a Table, after insertion, modification or deletion.
Syntax:-
connectionobject.commit()

Closing a Connection
When we open a connection, then we must also clear the environment using close().
Syntax:-
connectionobject.close()

Python program to create a Database in MYSQL


import mysql.connector as msc
con=msc.connect(host="localhost",user="root",passwd="India@123")
E-SCHOOL

cur=con.cursor()
cmd="create database SMS"
cur.execute(cmd)
con.commit()
con.close()
If not sure that the database exists or not, then SQL command can be given as
cmd="create database if not exists SMS"

Python program to create a Table in MYSQL


import mysql.connector as msq
con=msq.connect(host=”localhost”,user=”root”,passwd=”india”,database=”myproject”)
cur=con.cursor()
cmd=”create table if not exists students(rno int,name varchar(20),marks float)”
cur.execute(cmd)
con.commit()
con.close()
Similarly we can use alter and drop table command.

Python program to add 2 records in Table in MYSQL


import mysql.connector as msc
con=msc.connect(host=”localhost”,user=”root”,password=”India@123”,database=”SMS”)
cur=con.cursor()
for I in range(1,3):
r=int(input(‘Enter roll number of student’))
n=input(‘Enter name of student’)
m=float(input(‘Enter marks’))
cmd=”insert into students values({},’{}’, {})”.format(r,n,m)
cur.execute(cmd)
con.commit()
con.close()

For String and date values {} must be used within ‘ ’ and date should be entered as
yyyy-mm-dd
E-SCHOOL

Python program to modify records in Table in MYSQL


import mysql.connector as msc
con=msc.connect(host=”localhost”,user=”root”,password=”India@123”,database=”SMS”)
cur=con.cursor()
cmd=”update students set marks=marks+10”
cur.execute(cmd)
con.commit()
con.close()

Python program to delete records from a Table in MYSQL


import mysql.connector as msc
con=msc.connect(host=”localhost”,user=”root”,password=”India@123”,database=”SMS”)
cur=con.cursor()
cmd=”delete from students where marks>90”
cur.execute(cmd)
con.commit()
con.close()

Python program to display all records from Table Students


Assuming a table Students in database grmxii

import mysql.connector as msc


con=msc.connect(host="localhost",user="root",passwd="India@123",database="grmxii")
cur=con.cursor()
cmd="select * from students"
cur.execute(cmd)
t=cur.fetchall()
print(t)
E-SCHOOL

con.close()
OUTPUT
[(101, 'Aman Kapoor', 99.0), (102, 'Raka', 78.0), (106, 'Billu', 99.0)]

Python program to display one record from Table Students


import mysql.connector as msc
con=msc.connect(host="localhost",user="root",passwd="India@123",database="grmxii")
cur=con.cursor()
cmd="select * from students"
cur.execute(cmd)
t=cur.fetchone()
print(t)
con.close()
OUTPUT
(101, 'Aman Kapoor', 99.0)

Python program to display TWO records from Table Students


import mysql.connector as msc
con=msc.connect(host="localhost",user="root",passwd="India@123",database="grmxii")
cur=con.cursor()
cmd="select * from students"
cur.execute(cmd)
t=cur.fetchmany(2)
print(t)
con.close()
OUTPUT
[(101, 'Aman Kapoor', 99.0), (102, 'Raka', 78.0)]

Python program to display all records one by one from Table Students
import mysql.connector as msc
con=msc.connect(host="localhost",user="root",passwd="India@123",database="grmxii")
cur=con.cursor()
cmd="select * from students"
E-SCHOOL

cur.execute(cmd)
records=cur.fetchall()
for row in records:
for cols in row:
print(cols,end="\t")
print()
con.close()
OUTPUT
101 Aman Kapoor 99.0
102 Raka 78.0
106 Billu 99.0

Python program to count number of records from Table Students


import mysql.connector as msc
con=msc.connect(host="localhost",user="root",passwd="India@123",database="grmxii")
cur=con.cursor()
cmd="select * from students"
cur.execute(cmd)
cur.fetchall()
print("Total records:-",cur.rowcount)
con.close()

OUTPUT
Total records:- 3

Parameterised Queries
There are two methods of using parameterized query.

Old method
In this method we write a command in following way:
r=int(input("Enter Rno"))
n=input("Enter Name")
cmd="select * from students where rno=%s or name='%s' " % (r,n)
E-SCHOOL

New method
In this method we write a command in following way:
r=int(input("Enter Rno"))
n=input("Enter Name")
cmd="select * from students where rno={} or name='{}’ ".format(r,n)

You might also like