0% found this document useful (1 vote)
83 views6 pages

XII CS Python MySQL Connectivity Notes

class 12 cbse sql notes #computerscience

Uploaded by

nikhita4775
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (1 vote)
83 views6 pages

XII CS Python MySQL Connectivity Notes

class 12 cbse sql notes #computerscience

Uploaded by

nikhita4775
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

COMPUTER SCIENCE

CLASS-XII
Python MySQL Connectivity Notes
Five major steps for connecting MySQL and Python

1. Import the package mysql.connector


2. Create a connection Object
3. Create a cursor instance
4. Execute a query
5. Clean up the environment
Step-1:
Import the package MySQL Connector
Syntax:
import mysql.connector
OR
import mysql.connector as sq
Note:
If no Error occur after executing the above import statement, then it means MySQL
connector is working properly.
Step-2:
Create a connection Object.
The connect() function of mysql.connector package is used to establish a connection
to MySQL database.
Syntax :
<Connection-Object>=mysql.connector.connect(host=<hostname>,
user=<username>,passwd=<password>,[database=<database>])
Here,
 Host Name : It is the server name or IP address on which your MySQL is
running.
 User Name : It is given to work with MySQL server, the default username is
“root”.
 Password : It is given by the user at the time of installation of the MySQL
database.
Note:
You can write “password” OR “passwd”.
 Database: It is the database name of a MySQL database. This is an optional

pg. 1
parameter.
Step-3:
Create a Cursor Instance.
Next step, is to use the connection object returned by the connect() method to
create a cursor object. You can create a cursor object using the cursor() method of
the connection object. The cursor object is used to execute statements to perform
database operations.
Syntax:-
<cursor-object>= <connection-object>.cursor()
For Example:-
cur=ob.cursor()
Here cur is the cursor object created using connection object ob using cursor()
method.
Step-4:
Execute a Query.
Once you have created a cursor, you can execute SQL query using execute() function
with cursor object.
Syntax :
cursor-object.execute(“SQL Query string”)
For Example :
cur.execute(“select * from Employee")
Here, cur is a cursor object which uses execute method to run the SQL query is given
in the form of a string.
Note:
You can execute any SQL query with the help execute() method.
Step-5:
Clean up the Environment.
Once the processing on MySQL database is over the connection as well as cursor is
closed by using close() method of the corresponding object.
 Close the MySQL database connection using
<Connectionobject>.close()
For Example :
ob.close()
 Close the cursor object using a <cursor object> .close()
For Example :
cur.close()
pg. 2
Simple code to connect MySQL and Python.
import mysql.connector as sql
db=sql.connect(host="localhost",user="root",passwd="1234",)
if db.is_connected():
print("successfully connected")
else:
print(“Not connected")

Mycur=db.cursor()
Mycur.execute("create database Employee")
print("successfully created the Database")
Mycur.close()
db.close()

Commit() function:
After performing any DML operation such as insert, update and delete, it is
mandatory to commit the DML by executing commit () from DB connector object.
Otherwise the changes will not get reflected in the data base object(table)
Syntax :
<Connection object>.commit()
Example :
ob.commit()

Test Yourself:
1. Name the file we import in Python to establish my SQL Python connectivity
Ans: mysql.connector
2.Write a statement to create a cursor for the connection.
Ans: cur=mydb.cursor()

3.Write the command Modify the salary and increase it by 1000, for all who get
salary less than 6000 in Employee.
Ans: UPDATE Employee SET Salary = Salary+1000 WHERE
Salary<6000;

4. Make the changes permanent in the database.


Ans: commit()
pg. 3
EXTRACT DATA FROM RESULT SET
Whenever we used to retrieve records from the database using select command we
need the following functions:
 fetchone() : This method retrieves the first record of the database in the form
of list/tuple, next time it will fetch the second record. if no more rows are
available it returns None.
Syntax : <identifier>=<cursor identifier>.fetchone()
 fetchmany(n) : This Method fetches the next set of rows of a query and return
a list of tuple. The number of rows returned can be specified using the n
argument, which default to one. If no more rows are available it returns an
empty list.
Syntax : <identifier>=<cursor identifier>.fetchmany(n)
 fetchall() : It fetches all records from the database and it returns a list of tuple.
Syntax : <identifier>=<cursor identifier>.fetchall()
rowcount
 It is not a function, It is the property of a cursor object.
 It is used to return the number of rows returned for SELECT statements, or the
number of rows effected by DML statement such as INSERT, UPDATE, etc.
Syntax :
<identifier>= <cursor object>.rowcount
For Example:
data=cur.rowcount
Note :- rowcount is an attribute.
Example of Sample code to formatting the query

Previous year questions:


pg. 4
Q.1. The code given below intends to delete a record from the table ‘Employee’
available in the database ‘Company’, whose ‘Dept’ is ‘Elect’ and Grade is ‘G4’. Write
the following missing statements to complete the code:
Statement 1-To form the cursor object
Statement 2-To execute the command that will delete the desired record from the table
‘Employee’.
Statement 3-To make the changes after deletion of record permanently in the database.
import mysql.connector as mycon
mydb=mycon.connect(host=‘localhost’, database=‘Company’,
user= ‘root’, passwd= ‘1234’)
mycursor=______________ #Statement 1
mycursor.execute ( _______________________ ) #Statement 2
mydb.____________ #Statement 3
Answer:
Statement 1:mydb.cursor()
Statement 2: DELETE FROM Employee WHERE Dept= ‘Elect’ AND Grade=‘G4’
Statement 3: commit()

Q.2.The management of a company has decided to increase the salary by 20% of all
those employees who belong to the ‘Dept’ (IT). Now, write the following missing
statements to complete the code:
Statement 1-To form the cursor object
Statement 2-To execute the command that will increase the salary by 20% of all those
employees who belong to the ‘Dept’ (IT).
Statement 3-To make the changes after deletion of record permanently in the
database.
import mysql.connector as mycon
mydb=mycon.connect(host=‘localhost’, database=‘Company’,
user= ‘root’, passwd= ‘1234’)
mycursor=______________ #Statement 1
mycursor.execute ( _______________________ ) #Statement 2
mydb.____________ #Statement 3
Answer:
Statement 1:mydb.cursor()
Statement 2:UPDATE Employee SET Salary=Salary+0.2*Salary
WHERE Dept= ‘IT’
Statement 3: commit()

pg. 5
Sample Program:
import mysql.connector as m
mycon=m.connect(host='localhost',user='root',passwd='Tiger',
database='SCHOOL')
cur=mycon.cursor()
cur.execute("select * FROM Student")
y=cur.fetchall()
for i in y:
print(i)
cur.close()
mycon.close()
OUTPUT:
(10, 'Sai Satyam', 'XI', 97.2)
(11, 'Omm Prakash', 'X', 92.0)
(12, 'Amit Kumar', 'XII', 87.3)
(14, 'Mehek Gupta', 'XI', 97.3)
(15, 'Narendra', 'X', 89.4)
(17, 'Harshit Meheta', 'X', 85.9)

pg. 6

You might also like