KEMBAR78
MySql Interface database in sql python my.pptx
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()

MySql Interface database in sql python my.pptx

  • 1.
  • 2.
    Steps for creatingDatabase 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 thePackages: 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 connectionto 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.connectoras 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 aCursor 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 SQLquery : 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 adatabase “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 displayall 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 Createa 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, DELETEand 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 insertnew 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 insertnew 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 studentVALUES({},'{}', {},'{}')".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 Deletea 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("Recordnot found") else: mycon.commit() print(mycur.rowcount,"Record Deleted") ‘’’
  • 18.
    # to Updatea 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 Updatea 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 fromResultset : 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() Itwill 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>) Itwill 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 fetchone 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.
  • 24.
  • 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 byQuery. 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 usedmy_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 Upthe Environment After all processing, the connection must be closed. <connectionobject>.close()