The document provides a comprehensive guide on how to connect to a MySQL database using the mysql-connector-python library in Python. It includes installation instructions, steps for creating database connectivity, executing SQL queries, and performing insert, update, and delete operations. Additionally, it covers how to create databases and tables, as well as how to fetch data from the database using various methods.
The document provides a comprehensive guide on how to connect to a MySQL database using the mysql-connector-python library in Python. It includes installation instructions, steps for creating database connectivity, executing SQL queries, and performing insert, update, and delete operations. Additionally, it covers how to create databases and tables, as well as how to fetch data from the database using various methods.
Introduction
- When you design real life applications, you are
bound to encounter situations wherein you need to
manipulate data stored in a database through an
application designed by you.
+ In order to connect to a database from within the
python , you need a library that provides connectivity
functionality. There are so many libraries , but we
will use mysql connector library.— Installing
“Write the following command:
pip install mysql-connector-python
in the command prompt.
-After installing , open Python shell and write
import mysql.connector
*If it will not show any error , it means you have
successfully installed it.__Steps for creating Database Connectivity
Import the package mysql.connector
Open a connection to a database
Re EOC Led
rere Ne tang
| Source me Tec Ney UB uScIel (aco
(ech mer Menno rn agimport mysql.connector
import mysql.connector
or
import mysql.connector as sqltor
oe
eensi
Open a connection to a mysq! database
con=mysql.connector.connect(host = ,
user = ,
password = ,
database=)
(connect ()is the function used to establish connection betweer
Python and MySQL. connect() method uses 4 arguments which
are keyword arguments)
con=mysql.connector.connect(host = ‘localhost’ ,
user = ‘root’ ,
password = ‘1234,
database= ‘school’)= ————e
Create cursor instance
A database cursor is a special control structure that facilitates
the row by row processing of records in the resultset , i.e. set of
records retrieved as per query.
= . cursor()
Execute SQL query
Once you have created a cursor , you can execute SQL query
using execute() function with cursor object.
Syntax:
. execute()Example
import mysql . connector
con = mysql . connector . connect ( host = “localhost” ,
user = “root” ,
password = “123”)
cur = con. cursor ()
cur. execute(“create database student”)
print (“query executed”)Extract data fromre
data = cursor . fetchall() - Returns all the records retrieved as
per query ina tuple form.
data = cursor . fetchone() - It will return one record from the
resultset as a tuple. First time , it will fetch the first record,
next time it will fetch the second record. If there is nothing to
fetch then it will return None
data = cursor . fetchmany(n) - This method fetches n records
in the form of a tuple. If nothing is mention then it will return
one value. If there is nothing to fetch then it will return [].
variable = cursor . rowcount - This property of a cursor returns
the number of rows retrieved.import mysql . connector
con = mysql . connector . connect ( host = “localhost” ,
user = “root” ,
password = “123” ,
database =“school”)
cur = con. cursor ()
cur . execute(“select* from student”)
data=cur. fetchall()
for i in data:
print(i)
print(“Total no. of rows retrieved” , cur.rowcount)Example
import mysql . connector
con = mysql . connector . connect ( host = “localhost” ,
user = “root” ,
password = “123” ,
database =“school”)
cur = con. cursor ()
cur. execute(“select* from student”)
data=cur. fetchone()
print(i)
print(“Total no. of rows retrieved” , cur.rowcount)import mysql . connector
con = mysql . connector . connect ( host = “localhost” ,
user = “root” ,
password = “123” ,
database =“school”)
cur = con. cursor ()
cur. execute(“select* from student”)
data=cur. fetchmany(4) #it will fetch first 4 records
for i in data:
print(i)
print(“Total no. of rows retrieved” , cur.rowcount)
data=cur. fetchmany(4) #it will fetch next 4 records
for i in data:
print(i)
print(“Total no. of rows retrieved” , cur.rowcount)(When we want user to input , then we use parameterized queries)
(i) Old Style : String Templates with % formatting
fv
Where,
fis a template string (it is a string ie. Query of SQL)
v specifies the values to be formatted using the template.
v must bea tuple.
“select * from student where name=‘ %s’ ” % (‘akash’,)
(NOTE: %v is the value. In the above example %s is the format specifier which will be
replaced by the value i.e. 70. the value in the bracket should bea tuple, if there is
only one value then it becomes compulsory to put comma(,). If the value is string
then %s will be in single quotes)ew Style : String Template with % formatting
str= “select * from student where marks > {} and
section = ‘{}’ “ . format (70,'B’)
Example-1
import mysql . connector
con=mysql . connector . connect (host=localhost’ , password=123’ ,
user=root’ , database=‘school’ )
if con. is_connected() :
print(“connection successfully”)
cur= con.cursor()
cur.execute(“select * from student where avgmark>85”)
data=cur.fetchall()
for i in data:
print(i)Example-2
(Take input from user)
import mysql . connector
con=mysq] . connector . connect (host=‘localhost’ , password='123’ ,
user=root’ , database=‘school’ )
if con. is_connected() :
print(“connection successfully”)
cur= con.cursor()
m=int(input(“enter marks:”))
query=“select * from student where avgmark > %s” % (m,)
cur.execute(query)
data=cur.fetchall()
fori in data:
print(i)Example-3
(Take more than 1 input from user)
import mysql . connector
con=mysql . connector . connect (host=‘localhost’ , password='123’ , user=root’ ,
database=‘school’ )
if con. is_connected() :
print(“connection successfully”)
cur= con.cursor()
m=int(input(“enter marks:”))
s= input(“enter stream:”)
query=“select * from student where avgmark > %s and stream=‘%s’” % (m,s)
cur.execute(query)
data=cur.fetchall()
for iin data:
print(i)Example-4
(Using New Style method)
import mysql . connector
con=mysql . connector . connect (host=‘localhost’ , password="123’ , user=root’ ,
database=‘school’ )
if con. is_connected() :
print(“connection successfully”)
cur= con.cursor()
m=int(input(“enter marks:”))
s= input(“enter stream:”)
query=“select * from student where avgmark >{} and stream= ‘{}
cur.execute(query)
data=cur.fetchall()
for iin data:
print(i)
. format (m,s)insert, update and delete operations
insert operation
import mysql! . connector
con=mysql . connector . connect (host=‘localhost’ , password='123’ , user=root’ ,
database=‘school’ )
cur= con.cursor()
r= int( input(“enter rollno”) )
n= input(“enter name”)
int( input(“enter marks”) )
s = input(“enter stream”)
query= “insert into std values( {} , ‘{}’ , {}, {}’ )” .format(r,n,m,s)
cur.execute(query)
con.commit() # to reflect the values in the database we use commit() function.
print(“row inserted successfully”)update operation
import mysql . connector
con=mysql . connector . connect (host='localhost’ , password='123’ , user=root’ ,
database=‘school’ )
cur= con.cursor()
query= “ update std set marks=50 where rollno=9”
cur.execute(query)
con.commit() # to reflect the values in the database we use commit() function.
print(“row updated successfully”)delete operation :
import mysql . connector
con=mysql . connector . connect (host=‘localhost’ , password="123’ , user=root’ ,
database=‘school’ )
cur= con.cursor()
s =input(“enter stream”)
query= “delete from std where stream= ‘{}’ ” .format(s)
cur.execute(query)
con.commit() # to reflect the values in the database we use commit() function.
print(“row(s) deleted successfully”)Create database
import mysql . connector
con=mysql . connector . connect (host=‘localhost’ , password=123’ , user=root’ )
cur= con.cursor()
cur.execute(“create database books”)
print(“database created”)
Create table
import mysql] . connector
con=mysql . connector . connect (host=‘localhost’ , password="123’ , user=root’ ,
database =‘books’ )
cur= con.cursor()
cur.execute(“create table compsci( Bno integer , Bname varchar(40) , Price
float)”)
print(“table created”)Insert values in table
import mysql . connector
con=mysql . connector . connect (host=‘localhost’ , password='123’ , user=root’,
database=‘books’ )
cur= con.cursor()
while True :
int(input(“enter book number:”))
put(“enter book name:”)
p=float(input(“enter price:”))
query=“insert into compsci values ({} , ‘{}’, {})” . format(no , n, p)
cur.execute(query)
con.commit()
print(“row inserted”)
ch= input( “do you want to continue?(y/n) ” )
if ch ==‘n’:
break