Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

INTERFACE PYTHON WITH MYSQL – MATERIAL for row in data:

print(row)
NAME OF THE STUDENT: ____________________________
(B)<data>=<cursor>.fetchone().
There are many different libraries available for Python to It will return only one row(record) from the resultset in
accomplish this. the form of a tuple containing a record. A pointer is
We shall work with mysql connector library. initialized which points to the first record of the resultset
Steps for creating database connectivity applications: as soon as you execute a query. It returns the record
(1) Start python pointed to by this pointer.
(2) Import required packages When you fetch one record, the pointer moves to
( import mysql.connector or next record of the recordset. So next time, if you execute
import mysql.connector as c) (aliasing) the fetchone( ) method, it will return only one record
(3) Open a connection to database pointed to by the pointer and after fetching, the pointer
A database connection object controls the will move to the next record of the resultset.
connection to the database. It represents a unique If there are no more records, then it returns None.
session with a database connected from within a Ex: data=cursor.fetchone()
script/program. print(data)
Syntax: <connection-obj>=mysql.connector.connect (C) <data>=<cursor>.fetchmany(<n>).
(host=<host-name>,user=<username>, The fetchmany(<n>) method will return only the <n>
password=<password>, [,database=<database>]) number of rows from the resultset in the form of a tuple
Ex: containing the records.
mycon=mysql.connector.connect(host="localhost", If there are not more records then it returns an empty
user="root",password="1234",database="jnv") tuple.
if mycon.is_connected(): Ex: data=cursor.fetchmany(4)
print(“Successfully connected”) count=count.rowcount
else: print(“Total Rows: “,count)
print(“Not connected to mysql database”) for row in data:
(4) Create a cursor instance: print(row)
When you connect to a database from within a
script/program, then the query gets sent to the server, (D)<variable>=<cursor>.rowcount. The rowcount is a
where it gets executed, and the resultset (the set of property of cursor object, it always returns how many
records retrieved as per query) is sent over the records have been retrieved so far using any of the
connection to you, in one go. Database Cursor is a fetch() methods.
special control structure that facilitates the row by row data=cursor.fetchone()
processing of records in the resultset i.e. the set of count=cursor.rowcount
records retrieved as per query. print(“Total records till now: “,count)
Ex: cursor=mycon.cursor() data=cursor.fetchmany(3)
(5) Execute a query: <cursorobect>.execute(<sql query string>) count=cursor.rowcount
Ex: cursor.execute(“select * from student”) print(“Total records till now: “,count)
(if you want to view all the records of table student) Output: Total records till now:1
“The above code will execute the given SQL Query and store Total records till now:4
the retrieved records (i.e. resultset) in the cursor object (7) Clean up the environment: Need to close the
(cursor), which we can use in our programs/scripts as required. connection established.
(The result set refers to a logical set of records that are Ex: conn.close()
fetched from the database by executing an SQL query
and made available to the application program)
(6) Extract data from result set : Record Program 1: Write a python program that
Can use any of the following fetch( ) functions. displays all rows fetched from student table of mysql
(A) <data>=<cursor>.fetchall(). database “jnv”.
It will return all the rows(records) from the resultset in (User is “root” and password is “1234”)
the form of a tuple containing the records.
import mysql.connector
data=cursor.fetchall()
mycon=mysql.connector.connect(host="localhost",
count=cursor.rowcount
user="root",password="1234",database="jnv",
print(“Total Rows :”,count)
auth_plugin="mysql_native_password")
if mycon.is_connected(): Ex 3:
print(“Successfully connected”) “{monster} has eaten {city}”.
else: format(city=’Tokyo’,monster=’Tsunami’)
print(“Not connected to mysql database”) Ex 4:
cursor=mycon.cursor( ); str=”select * from student where marks>{}
cursor.execute("select * from student") and section=’{}’ “.format(60,’A’)
data=cursor.fetchall( ) Then str stores
count=cursor.rowcount ”select * from student where marks>60 and section=’A’ “
print("Total number of rows retrieved...",count)
Record Program 2: Write a python program that creates
for row in data:
a table books, insert data from that table, fetch data
print(row)
from the table of mysql database “jnv”
mycon.close()
(User is “root” and password is “1234”)
Sample Output:
Successfully connected import mysql.connector
Total number of rows retrieved... 6 mycon=mysql.connector.connect(host="localhost",
(1000.0, 'pradeep', 75.5, 95.0, 57.0, 227.5, 75.8333, 'First', None) user="root",password="1234",database="jnv",
(1001.0, 'sudeep', 77.5, 95.0, 68.5, 241.0, 80.3333, 'First', None)
(1002.0, 'philip', 32.5, 60.0, 59.5, 152.0, 50.6667, 'Fail', None)
auth_plugin="mysql_native_password")
(1003.0, 'pradeep', 45.5, 65.5, 70.0, 181.0, 60.3333, 'First', None) cursor=mycon.cursor();
(1004.0, 'naidu', 77.5, 25.5, 65.5, 168.5, 56.16, 'Fail', 8598) cursor.execute("create table books(bookid int,bookname
(1005.0, 'sudeep', 80.5, 72.5, 67.0, 220.0, 73.3333, 'First', None) char(20),bookprice float)")
Parameterized Queries: choice='Y'
Ex: jnp=50 while choice not in ['n','N']:
select * from student where marks>jnp bid=int(input("Enter Book ID: "))
bname=input("Enter Book Name: ")
(i) old style string templates with % formatting bprice=float(input("Enter Book Price: "))
Syntax: f%v str="INSERT INTO books(bookid,bookname,bookprice)
Where f is a template string and v specified the value to values({},'{}',{})".format(bid,bname,bprice)
be formatted using that template. cursor.execute(str)
(A) Ex: choice=input("Do you want to continue? (Y/N)")
str=”select * from student where marks>%s” %(70, ) mycon.commit( )
cursor.execute (str) cursor.execute("select * from books")
data=cursor.fetchall() bookdata=cursor.fetchall()
for row in data: count=cursor.rowcount
print(row) print("Total number of books rows retrieved...",count)
(B)With multiple arguments for row in bookdata:
str=”select * from student where marks>%s and print(row)
section = ‘%s’ “ %(60,’A’) mycon.close()
cursor.execute (str) Sample Data:
data=cursor.fetchall() Enter Book ID: 1001
for row in data: Enter Book Name: C++
print(row) Enter Book Price: 255.0
(c) memory=32 Do you want to continue? (Y/N)y
id=2 Enter Book ID: 1002
input=(memory,id) Enter Book Name: Python
query=”update computers set memory =%s where Enter Book Price: 325.5
id=%s” Do you want to continue? (Y/N)Y
cursor.execute(query,input) Enter Book ID: 1003
(ii) New style string templates with % formatting: Enter Book Name: SQL
format( ) method uses its arguments to substitute an Enter Book Price: 525.0
appropriate value for each format code in the template. Do you want to continue? (Y/N)N
Ex 1: “We have {0} hectares planted to {1}.”.format(49,”okra”) Total number of books rows retrieved... 3
We have 49 hectares planted to okra.
(1001, 'C++', 255.0)
Ex 2: “We have { } hectares planted to { }.”.format(49,”okra”)
We have 49 hectares planted to okra.
(1002, 'Python', 325.5)
(1003, 'SQL', 525.0)

You might also like