Test Index

Interface of Python with SQL Database Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 2 of 10
Marks: +1, -0
A table named EQUITY in INVESTMENT database has the following structure :
FieldTypeRemarks
CodeChar(6)Code of stock
NameVarchar(15)Name of stock
ExchangeChar(3)Name of exchange
LTPFloatLast traded Price
VolumeintAmount of stock
Write a function in Python to display all the records where Exchange is BSE from the EQUITY table. Also display the total number of such records.
Assume the following for Python database connectivity :
• Host – localhost
• User – Finman
• Password – Stk2026
[CBSE 2026 Compartment]
Solution:  
Concept: Python–MySQL connectivity steps: import mysql.connector, connect with connect() (host, user, password, database), create a cursor, run the query with execute(), fetch the rows with fetchall(), and close the connection.
import mysql.connector
def DisplayBSE():
con = mysql.connector.connect(host="localhost", user="Finman",
password="Stk2026", database="INVESTMENT")
cur = con.cursor()
cur.execute("SELECT * FROM EQUITY WHERE Exchange = 'BSE'")
records = cur.fetchall()
for rec in records:
print(rec)
print("Total number of records:", cur.rowcount)
con.close()
Explanation:
1. connect() opens a link to the INVESTMENT database on localhost with the given user and password.
2. con.cursor() gives the cursor object used to send SQL statements.
3. The WHERE clause keeps only the rows whose Exchange is 'BSE'.
4. fetchall() returns all those rows as a list of tuples; the loop prints each record.
5. After fetching, cur.rowcount holds the number of rows retrieved (len(records) gives the same count).
6. con.close() releases the connection.
Key point: Call fetchall() before reading rowcount; for a SELECT, the count is known only after the rows are fetched.
© examsnet.com
Advertisements
Go to Question: