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

Python Database

Python can be used to interface with MySQL databases. MYSQL is used as the backend to store data, while Python acts as the frontend to build user interfaces. The mysql.connector package must be installed to connect Python to MySQL. A connection object is created using the connect() method, which requires parameters like host, user, password, and database name. A cursor object is then created and used to execute SQL queries and extract data from the result set. Functions like fetchall(), fetchone(), commit(), and close() help retrieve, save, and close the database connection.

Uploaded by

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

Python Database

Python can be used to interface with MySQL databases. MYSQL is used as the backend to store data, while Python acts as the frontend to build user interfaces. The mysql.connector package must be installed to connect Python to MySQL. A connection object is created using the connect() method, which requires parameters like host, user, password, and database name. A cursor object is then created and used to execute SQL queries and extract data from the result set. Functions like fetchall(), fetchone(), commit(), and close() help retrieve, save, and close the database connection.

Uploaded by

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

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”)
or
<connectionobject> = msc.connect(“localhost”,”root”,”password”,”dbname”)

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 or passwd:- 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.”

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")
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

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)
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"
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)
Note: For string values %s is enclosed within single quotes (‘ ‘).

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