0% found this document useful (0 votes)
9 views3 pages

Python MySQL Connection Q&A Guide

Uploaded by

muniraj46567
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Python MySQL Connection Q&A Guide

Uploaded by

muniraj46567
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python – MySQL Connectivity Revision Questions with

Solutions

1. Short Answer – Theory

Q1. Write the steps to connect Python with a MySQL database.


Answer:

1. Import the module


2. import [Link]
3. Establish a connection
4. mycon = [Link](host='localhost', user='root',
passwd='xxxx', database='school')
5. Create a cursor object
6. cursor = [Link]()
7. Execute SQL queries
8. [Link]("SELECT * FROM student")
9. Fetch results (if required)
10. data = [Link]()
11. Close connection
12. [Link]()

2. Output Prediction

Q2.

import [Link] as sql


con = [Link](host="localhost", user="root", passwd="1234",
database="school")
cur = [Link]()
[Link]("SELECT Name, Marks FROM student WHERE Marks > 80")
for row in [Link]():
print(row[0], "-", row[1])

If the table student has:

RollNo Name Marks


1 Amit 85
2 Priya 78
3 Rohan 92

Output:

Amit - 85
Rohan - 92

3. Error Finding
Q3. Identify and correct the error:

import [Link]
mycon = [Link]("localhost", "root", "1234", "school")

Answer:
connect() should use keyword arguments:

mycon = [Link](host="localhost", user="root",


passwd="1234", database="school")

4. Query Execution

Q4. Write a Python program to:

 Connect to a MySQL database school


 Insert a record into table student(RollNo INT, Name VARCHAR(30), Marks INT)
 Commit and close the connection

Answer:

import [Link]

mycon = [Link](host="localhost", user="root",


passwd="1234", database="school")
cur = [Link]()

qry = "INSERT INTO student VALUES (%s, %s, %s)"


data = (4, 'Neha', 88)

[Link](qry, data)
[Link]()

print("Record inserted successfully")


[Link]()

5. Fetching Data – Board Style

Q5. Write a Python program to display the names of students scoring between 70 and 90
from student table.

Answer:

import [Link]

mycon = [Link](host="localhost", user="root",


passwd="1234", database="school")
cur = [Link]()

[Link]("SELECT Name FROM student WHERE Marks BETWEEN 70 AND 90")


for row in [Link]():
print(row[0])
[Link]()

6. Board-Level Integrated Question

Q6. A table EMPLOYEE has the following data:

EID NAME SALARY


101 Rahul 45000
102 Meena 52000
103 Arjun 48000

Write a Python program to:

1. Connect to MySQL
2. Display the details of employees with salary > 48000

Answer:

import [Link]

con = [Link](host="localhost", user="root", passwd="1234",


database="company")
cur = [Link]()

[Link]("SELECT * FROM EMPLOYEE WHERE SALARY > 48000")


for row in [Link]():
print(row)

[Link]()

Output:

(102, 'Meena', 52000)

Common questions

Powered by AI

Using keyword arguments when establishing a MySQL connection in Python is important because it improves code readability and prevents errors. For instance, specifying the host, user, password, and database as keyword arguments avoids confusion about parameter order and makes the code more understandable and less error-prone .

In Python, a cursor object enables interaction with the database. It acts as an intermediary for executing queries and fetching results. You can execute SQL commands via a cursor, and use functions like cursor.fetchall() to retrieve query results. It helps in managing the context of the data and maintains the session state .

Using a parameterized query in Python when inserting data into a MySQL database enhances security by preventing SQL injection. It also fosters code clarity and maintainability, as the logic of the code is separated from the data presented. It ensures that data is safely handled by allowing placeholders in queries that are later filled with specific values, minimizing the risk of malicious data exploitation .

Failing to properly close a MySQL database connection in a Python application can lead to resource leaks, as each open connection consumes system resources. This can result in degraded performance, increased memory usage, and even hitting the maximum allowed number of simultaneous connections, causing subsequent connection attempts to fail until some are released .

The output of a SQL SELECT query is directly influenced by the conditions specified in the WHERE clause, which filters the records returned from the database. For example, if a query is executed to select names and marks from a 'student' table where marks are greater than 80, it will only return those records that meet this condition. If the 'student' table contains names and marks of students like Amit with 85 and Rohan with 92, only these rows will be included in the output .

Using non-keyword arguments in a MySQL connection string can lead to potential errors because it increases the likelihood of swapping or misinterpreting values, as demonstrated when connecting to databases without specifying keywords like host, user, passwd, and database. Best practices include using keyword arguments for clarity and reducing syntax errors, ensuring parameters are correctly aligned with their values .

If the host and database fields are incorrectly specified during a MySQL connection in Python, a connection to the intended database cannot be established, leading to operational errors such as 'Can't connect to MySQL server on specified host'. Also, incorrect databases will prevent access to the necessary data, impacting application's functionality .

The execution of the SQL query 'SELECT Name FROM student WHERE Marks BETWEEN 70 AND 90' filters the 'student' database to retrieve names of students whose marks fall within the specified range of 70 to 90. The query doesn’t retrieve other attributes like roll numbers or marks themselves, only names that satisfy the condition, ensuring a targeted fetch operation .

If a transaction is not committed after executing a data insertion query, the changes may not be saved to the database, especially in systems where auto-commit is turned off. This means any inserted records will be lost once the connection is closed. Additionally, it can lead to data inconsistency and integrity issues, as other operations may not account for uncommitted data .

To connect a Python application to a MySQL database, you need to: 1) Import the mysql.connector module, 2) Establish a connection using mysql.connector.connect() with appropriate parameters like host, user, passwd, and database, 3) Create a cursor object using the connection's cursor() method, 4) Execute SQL queries using cursor.execute(), 5) Fetch results if necessary using cursor.fetchall(), and 6) Close the connection using mycon.close().

You might also like