SlideShare a Scribd company logo
Interface python with SQL
Database
Steps for creating Database connectivity applications :
Steps :
1. Start Python
2. Import the Packages required for database programming
3. Open a connection to database
4. Crate a cursor instance
5. Execute a query
6. Extract data from result set
7. Clean up the environment
2. Import the Packages:
import mysql.connector
or
import mysql.connector as sqlcon
It will imports the MySQL connector module/ package in Python script
in our program.
Open a connection to MySQL Database
The connect() function of mysql.connector used to establish connection
to a MySQL database end returns a MySQLConnection object. It
requires four parameters host, user, passwd and databse.
<connectionobject> = mysql.connector.connect ( host=<hostname>, user=<username>,
passwd=<password> [,
databse=<database>])
Where host - the database server name;
default – “localhost”
username - the username on MySQL;
default –“root”
passwd – password of the user given at the time of installing MySQL database;
databse – optional; name of the database to which connectivity is to be established.
A database connection object controls the connection to the database. It represents a
unique session with a database connected from within a database connected from
within a script/ program
Ex: import mysql.connector as sqlcon
mycon=sqlcon.connect(host=”localhost”, user=”root”, passwd=”1234”,
databse=”school”)
Using is_connected() function with connected object of
MySQLConnection, we can verify whether connection is successful. It
will return True if, connection is successful.
# MYSQL database connection test import mysql.connector as sqlcon
mycon= sqlcon.connect(host="localhost", user="root", passwd="1234")
if mycon.is_connected():
print("Connected to MYSQL database successfully")
4. Create a Cursor Instance :
An instance of cursor is created with cursor() function. It returns a
cursor object which is use to execute SQL queries.
<cursorobject>= <connectionobject>.cursor()
A database cursor is a special control structure that facilitates the row
by row processing of records in the resultset.
Ex: mycur=mycon.cursor()
5 Execute SQL query :
SQL query can be executed using execute() function with cursor object.
<cursorobject>.execute(<SQL query statement>)
It will execute the SQL query and store the retrieved records i.e.
recordset in the cursorobject. The cursor is used to traverse the records
from the result set.
The recordset refers to a logical set of records that are fetched from the
database by executing SQL query and made available to the application
program.
# creating a database “school”
import mysql.connector as sqlcon
mycon= sqlcon.connect(host="localhost", user="root", passwd="1234")
#if mycon.is_connected():
# print("connected to MYSQL database successfully")
mycur= mycon.cursor()
mycur.execute("CREATE DATABASE school")
# to display all the databases present in
MySQL
import mysql.connector as sqlcon
mycon= sqlcon.connect(host="localhost", user="root", passwd="1234")
#if mycon.is_connected():
# print("connected to MYSQL database successfully")
mycur= mycon.cursor()
mycur.execute("SHOW DATABASES")
for x in mycur :
print(x)
# to Create a table student in MYSQL
database school using Python Interface
import mysql.connector as sqlcon
mycon= sqlcon.connect(host="localhost", user="root", passwd="1234",
database=”school”)
#if mycon.is_connected():
# print("connected to MYSQL database successfully")
mycur= mycon.cursor()
mycur.execute("CREATE TABLE student(rollno int(3) primary key, name
varchar(20), age integer, city char(10))")
Performing INSERT, DELETE and UPDATE
queries :
After INSERT, DELETE and UPDATE queries, it is must to run commit()
method with connection object for queries so that changes are
reflected in the database.
<connectionobject>.commit()
# to insert new record in the table student of
database school
import mysql.connector as sqlcon
mycon= sqlcon.connect(host="localhost", user="root", passwd="1234",
database="school")
mycur= mycon.cursor()
#if mycon.is_connected():
# print("connected to MYSQL database successfully")
mycur.execute("INSERT INTO student VALUES(1,'AMAN', 23 ,'GOA')")
mycon.commit()
print(mycur.rowcount,"Record Inserted")
# print("Record Inserted")
# to insert new record in the table student of
database school. Read data from user
import mysql.connector as sqlcon
mycon= sqlcon.connect(host="localhost", user="root", passwd="1234",
database="school")
mycur= mycon.cursor()
if mycon.is_connected():
print("connected to MYSQL database successfully") rollno=int(input("Enter
roll number"))
name=input("Enter name")
age=int(input("Enter age"))
city=input("Enter city")
mycur.execute("INSERT INTO student VALUES({},'{}',
{},'{}')".format(rollno,name,age,city))
‘’’ qry=("INSERT INTO student VALUES(%s,%s,%s,%s)")
data=(rollno,name,age,city) mycur.execute(qry, data) ‘’’
#mycur.execute("INSERT INTO student VALUES(%s,%s,%s,%s)",
(rollno,name,age,city))
mycon.commit() print(mycur.rowcount,"Record Inserted")
# to Delete a record in the table student of
database school
import mysql.connector as sqlcon
mycon= sqlcon.connect(host="localhost", user="root", passwd="1234",
database="school")
mycur= mycon.cursor()
#if mycon.is_connected():
# print("connected to MYSQL database successfully")
mycur.execute("DELETE FROM student WHERE rollno=101")
mycon.commit()
print(mycur.rowcount,"Record Deleted")
‘’’ if mycur.rowcount==0:
print("Record not found")
else:
mycon.commit()
print(mycur.rowcount,"Record Deleted") ‘’’
# to Update a record in the table student of
database school
import mysql.connector as sqlcon
mycon= sqlcon.connect(host="localhost", user="root", passwd="1234",
database="school")
mycur= mycon.cursor()
#if mycon.is_connected():
# print("connected to MYSQL database successfully")
mycur.execute("UPDATE student SET city=”Ranchi” WHERE rollno=101")
mycon.commit()
# to Update a record in the table student of
database school
print(mycur.rowcount,"Record Updated")
‘’’ if mycur.rowcount==0:
print("Record not found")
else:
mycon.commit()
print(mycur.rowcount,"Record Updated") ‘’’
Extract Data from Resultset :
Once the result of query is available in the form of a resultset stored in
a cursor object, we can extract data from the resultset using following
functions :
(i) <data>= <cursorobject>.fetchall()
It will return all the records retrieved as per query in a tuple form.
(ii) <data>= <cursorobject>.fetchone()
It will return one record from the resultset as a tuple. If there is no more
records then it return None. First time it will return the first record, next time
it will fetch the next record and so on.
NOTE : A pointer, points to the first record of the resultset as soon we
execute the query. Now when we fetch one more record, the pointer moves
to next record of the resultset and return one record only but rowcount()
function will return 2 because fetchone() method retrieved only 1 record but
SO FAR 2 records have been retrieved.
(iii) <data>= <cursorobject>.fetchmany(<n>)
It will return only the n number of rows from the resultset in the form
of tuple. If there are not more records then it returns an empty tuple.
(iv) <data>= <cursorobject>.
rowcount It returns the number of rows retrieved from the cursor so
far.
How to fetch one record of a table at run time
MySQLCursor.fetchone() Method
This method retrieves the next row of a query result set and returns a
single sequence, or None if no more rows are available. By default, the
returned tuple consists of data returned by the MySQL server,
converted to Python objects.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="r
oot",database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
row=mycursor.fetchone()
while row is not None:
print(row)
row = mycursor.fetchone()
MySQLCursor.fetchmany() Method
• rows = cursor.fetchmany(n)
• This method fetches the next set of rows of a query result and returns
a list of tuples. If no more rows are available, it returns an empty list
rowcount
Rows affected by Query. We can get number of rows affected by the query by
using rowcount. We will use one SELECT query here.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",data
base="school")
mycursor=mydb.cursor()
mycursor = mydb.cursor(buffered=True)
mycursor.execute("select * from student")
noofrows=mycursor.rowcount
print("No of rows in student table are",noofrows)
buffered=True
We have used my_cursor as buffered cursor.
my_cursor = my_connect.cursor(buffered=True)
This type cursor fetches rows and buffers them after getting output
from MySQL database. We can use such cursor as iterator. There is no
point in using buffered cursor for single fetching of rows.If we don’t use
buffered cursor then we will get -1 as output from rowcount
7. Clean Up the Environment
After all processing, the connection must be closed.
<connectionobject>.close()

More Related Content

PDF
24. SQL .pdf
PPTX
interface with mysql.pptx
PPTX
015. Interface Python with sql interface ppt class 12
PPTX
SQL-Connectivity python for beginners easy explanation with concepts and outp...
PPTX
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
PPTX
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PPTX
Interfacing python to mysql (11363255151).pptx
PPTX
Interface Python with MySQLwedgvwewefwefwe.pptx
24. SQL .pdf
interface with mysql.pptx
015. Interface Python with sql interface ppt class 12
SQL-Connectivity python for beginners easy explanation with concepts and outp...
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
Interfacing python to mysql (11363255151).pptx
Interface Python with MySQLwedgvwewefwefwe.pptx

Similar to MySql Interface database in sql python my.pptx (20)

PPTX
python db connection samples and program
PDF
Interface Python with MySQL.pdf
PPTX
Database connectivity in python
PPTX
Interface Python with MySQL connectivity.pptx
PDF
Interface python with sql database.pdf--
PDF
Interface python with sql database.pdf
PPTX
PYTHON MYSQL INTERFACE FOR CLASS XII STUDENTS
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
PPTX
Database Connectivity using Python and MySQL
PPTX
PythonDatabaseAPI -Presentation for Database
PDF
Interface python with sql database10.pdf
PPTX
unit-5 SQL 1 creating a databse connection.pptx
PDF
Mysql python
PPTX
Mysql python
PDF
dv-210220053508_removed.pdf
PPTX
3 PYTHON INTERACTION WITH SQLITE (concept of python)
PDF
015. Interface Python with MySQL.pdf
python db connection samples and program
Interface Python with MySQL.pdf
Database connectivity in python
Interface Python with MySQL connectivity.pptx
Interface python with sql database.pdf--
Interface python with sql database.pdf
PYTHON MYSQL INTERFACE FOR CLASS XII STUDENTS
Pyhton with Mysql to perform CRUD operations.pptx
Database Connectivity using Python and MySQL
PythonDatabaseAPI -Presentation for Database
Interface python with sql database10.pdf
unit-5 SQL 1 creating a databse connection.pptx
Mysql python
Mysql python
dv-210220053508_removed.pdf
3 PYTHON INTERACTION WITH SQLITE (concept of python)
015. Interface Python with MySQL.pdf
Ad

More from UshimArora (6)

PPTX
Social Impacts internet and social media awerness.pptx
PPTX
jati, shala samaja b.ed semester 3 .pptx
PPTX
MECHANICAL INJURIES helth relateddata and information.pptx
PPTX
LS 2 PPT.pptx
PPTX
ROLL NO 8.pptx
PPTX
roll nu 47.pptx
Social Impacts internet and social media awerness.pptx
jati, shala samaja b.ed semester 3 .pptx
MECHANICAL INJURIES helth relateddata and information.pptx
LS 2 PPT.pptx
ROLL NO 8.pptx
roll nu 47.pptx
Ad

Recently uploaded (20)

PPTX
neck nodes and dissection types and lymph nodes levels
PPTX
Introduction to Fisheries Biotechnology_Lesson 1.pptx
PDF
AlphaEarth Foundations and the Satellite Embedding dataset
PDF
Unveiling a 36 billion solar mass black hole at the centre of the Cosmic Hors...
PDF
Placing the Near-Earth Object Impact Probability in Context
PDF
HPLC-PPT.docx high performance liquid chromatography
PPTX
Comparative Structure of Integument in Vertebrates.pptx
PPTX
Introduction to Cardiovascular system_structure and functions-1
PPTX
Microbiology with diagram medical studies .pptx
PPTX
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
PPTX
EPIDURAL ANESTHESIA ANATOMY AND PHYSIOLOGY.pptx
PPTX
TOTAL hIP ARTHROPLASTY Presentation.pptx
PDF
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
DOCX
Q1_LE_Mathematics 8_Lesson 5_Week 5.docx
PDF
. Radiology Case Scenariosssssssssssssss
PPTX
Derivatives of integument scales, beaks, horns,.pptx
PDF
Cosmic Outliers: Low-spin Halos Explain the Abundance, Compactness, and Redsh...
PPTX
Taita Taveta Laboratory Technician Workshop Presentation.pptx
PPTX
BIOMOLECULES PPT........................
PPTX
ANEMIA WITH LEUKOPENIA MDS 07_25.pptx htggtftgt fredrctvg
neck nodes and dissection types and lymph nodes levels
Introduction to Fisheries Biotechnology_Lesson 1.pptx
AlphaEarth Foundations and the Satellite Embedding dataset
Unveiling a 36 billion solar mass black hole at the centre of the Cosmic Hors...
Placing the Near-Earth Object Impact Probability in Context
HPLC-PPT.docx high performance liquid chromatography
Comparative Structure of Integument in Vertebrates.pptx
Introduction to Cardiovascular system_structure and functions-1
Microbiology with diagram medical studies .pptx
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
EPIDURAL ANESTHESIA ANATOMY AND PHYSIOLOGY.pptx
TOTAL hIP ARTHROPLASTY Presentation.pptx
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
Q1_LE_Mathematics 8_Lesson 5_Week 5.docx
. Radiology Case Scenariosssssssssssssss
Derivatives of integument scales, beaks, horns,.pptx
Cosmic Outliers: Low-spin Halos Explain the Abundance, Compactness, and Redsh...
Taita Taveta Laboratory Technician Workshop Presentation.pptx
BIOMOLECULES PPT........................
ANEMIA WITH LEUKOPENIA MDS 07_25.pptx htggtftgt fredrctvg

MySql Interface database in sql python my.pptx

  • 1. Interface python with SQL Database
  • 2. Steps for creating Database connectivity applications : Steps : 1. Start Python 2. Import the Packages required for database programming 3. Open a connection to database 4. Crate a cursor instance 5. Execute a query 6. Extract data from result set 7. Clean up the environment
  • 3. 2. Import the Packages: import mysql.connector or import mysql.connector as sqlcon It will imports the MySQL connector module/ package in Python script in our program.
  • 4. Open a connection to MySQL Database The connect() function of mysql.connector used to establish connection to a MySQL database end returns a MySQLConnection object. It requires four parameters host, user, passwd and databse.
  • 5. <connectionobject> = mysql.connector.connect ( host=<hostname>, user=<username>, passwd=<password> [, databse=<database>]) Where host - the database server name; default – “localhost” username - the username on MySQL; default –“root” passwd – password of the user given at the time of installing MySQL database; databse – optional; name of the database to which connectivity is to be established. A database connection object controls the connection to the database. It represents a unique session with a database connected from within a database connected from within a script/ program
  • 6. Ex: import mysql.connector as sqlcon mycon=sqlcon.connect(host=”localhost”, user=”root”, passwd=”1234”, databse=”school”) Using is_connected() function with connected object of MySQLConnection, we can verify whether connection is successful. It will return True if, connection is successful. # MYSQL database connection test import mysql.connector as sqlcon mycon= sqlcon.connect(host="localhost", user="root", passwd="1234") if mycon.is_connected(): print("Connected to MYSQL database successfully")
  • 7. 4. Create a Cursor Instance : An instance of cursor is created with cursor() function. It returns a cursor object which is use to execute SQL queries. <cursorobject>= <connectionobject>.cursor() A database cursor is a special control structure that facilitates the row by row processing of records in the resultset. Ex: mycur=mycon.cursor()
  • 8. 5 Execute SQL query : SQL query can be executed using execute() function with cursor object. <cursorobject>.execute(<SQL query statement>) It will execute the SQL query and store the retrieved records i.e. recordset in the cursorobject. The cursor is used to traverse the records from the result set. The recordset refers to a logical set of records that are fetched from the database by executing SQL query and made available to the application program.
  • 9. # creating a database “school” import mysql.connector as sqlcon mycon= sqlcon.connect(host="localhost", user="root", passwd="1234") #if mycon.is_connected(): # print("connected to MYSQL database successfully") mycur= mycon.cursor() mycur.execute("CREATE DATABASE school")
  • 10. # to display all the databases present in MySQL import mysql.connector as sqlcon mycon= sqlcon.connect(host="localhost", user="root", passwd="1234") #if mycon.is_connected(): # print("connected to MYSQL database successfully") mycur= mycon.cursor() mycur.execute("SHOW DATABASES") for x in mycur : print(x)
  • 11. # to Create a table student in MYSQL database school using Python Interface import mysql.connector as sqlcon mycon= sqlcon.connect(host="localhost", user="root", passwd="1234", database=”school”) #if mycon.is_connected(): # print("connected to MYSQL database successfully") mycur= mycon.cursor() mycur.execute("CREATE TABLE student(rollno int(3) primary key, name varchar(20), age integer, city char(10))")
  • 12. Performing INSERT, DELETE and UPDATE queries : After INSERT, DELETE and UPDATE queries, it is must to run commit() method with connection object for queries so that changes are reflected in the database. <connectionobject>.commit()
  • 13. # to insert new record in the table student of database school import mysql.connector as sqlcon mycon= sqlcon.connect(host="localhost", user="root", passwd="1234", database="school") mycur= mycon.cursor() #if mycon.is_connected(): # print("connected to MYSQL database successfully") mycur.execute("INSERT INTO student VALUES(1,'AMAN', 23 ,'GOA')") mycon.commit() print(mycur.rowcount,"Record Inserted") # print("Record Inserted")
  • 14. # to insert new record in the table student of database school. Read data from user import mysql.connector as sqlcon mycon= sqlcon.connect(host="localhost", user="root", passwd="1234", database="school") mycur= mycon.cursor() if mycon.is_connected(): print("connected to MYSQL database successfully") rollno=int(input("Enter roll number")) name=input("Enter name") age=int(input("Enter age")) city=input("Enter city")
  • 15. mycur.execute("INSERT INTO student VALUES({},'{}', {},'{}')".format(rollno,name,age,city)) ‘’’ qry=("INSERT INTO student VALUES(%s,%s,%s,%s)") data=(rollno,name,age,city) mycur.execute(qry, data) ‘’’ #mycur.execute("INSERT INTO student VALUES(%s,%s,%s,%s)", (rollno,name,age,city)) mycon.commit() print(mycur.rowcount,"Record Inserted")
  • 16. # to Delete a record in the table student of database school import mysql.connector as sqlcon mycon= sqlcon.connect(host="localhost", user="root", passwd="1234", database="school") mycur= mycon.cursor() #if mycon.is_connected(): # print("connected to MYSQL database successfully") mycur.execute("DELETE FROM student WHERE rollno=101") mycon.commit() print(mycur.rowcount,"Record Deleted")
  • 17. ‘’’ if mycur.rowcount==0: print("Record not found") else: mycon.commit() print(mycur.rowcount,"Record Deleted") ‘’’
  • 18. # to Update a record in the table student of database school import mysql.connector as sqlcon mycon= sqlcon.connect(host="localhost", user="root", passwd="1234", database="school") mycur= mycon.cursor() #if mycon.is_connected(): # print("connected to MYSQL database successfully") mycur.execute("UPDATE student SET city=”Ranchi” WHERE rollno=101") mycon.commit()
  • 19. # to Update a record in the table student of database school print(mycur.rowcount,"Record Updated") ‘’’ if mycur.rowcount==0: print("Record not found") else: mycon.commit() print(mycur.rowcount,"Record Updated") ‘’’
  • 20. Extract Data from Resultset : Once the result of query is available in the form of a resultset stored in a cursor object, we can extract data from the resultset using following functions : (i) <data>= <cursorobject>.fetchall() It will return all the records retrieved as per query in a tuple form.
  • 21. (ii) <data>= <cursorobject>.fetchone() It will return one record from the resultset as a tuple. If there is no more records then it return None. First time it will return the first record, next time it will fetch the next record and so on. NOTE : A pointer, points to the first record of the resultset as soon we execute the query. Now when we fetch one more record, the pointer moves to next record of the resultset and return one record only but rowcount() function will return 2 because fetchone() method retrieved only 1 record but SO FAR 2 records have been retrieved.
  • 22. (iii) <data>= <cursorobject>.fetchmany(<n>) It will return only the n number of rows from the resultset in the form of tuple. If there are not more records then it returns an empty tuple. (iv) <data>= <cursorobject>. rowcount It returns the number of rows retrieved from the cursor so far.
  • 23. How to fetch one record of a table at run time MySQLCursor.fetchone() Method This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects.
  • 25. MySQLCursor.fetchmany() Method • rows = cursor.fetchmany(n) • This method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list
  • 26. rowcount Rows affected by Query. We can get number of rows affected by the query by using rowcount. We will use one SELECT query here. import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",data base="school") mycursor=mydb.cursor() mycursor = mydb.cursor(buffered=True) mycursor.execute("select * from student") noofrows=mycursor.rowcount print("No of rows in student table are",noofrows)
  • 27. buffered=True We have used my_cursor as buffered cursor. my_cursor = my_connect.cursor(buffered=True) This type cursor fetches rows and buffers them after getting output from MySQL database. We can use such cursor as iterator. There is no point in using buffered cursor for single fetching of rows.If we don’t use buffered cursor then we will get -1 as output from rowcount
  • 28. 7. Clean Up the Environment After all processing, the connection must be closed. <connectionobject>.close()