⚡0 XP🔥0

Ch 10 · Interface of Python with MySQL | पायथन और MySQL का संयोजन

Lesson 10 of 10 ⏱ 3 min read ❓ 5-question quiz ▶ Runs Python

Connecting Python to MySQL using mysql.connector - connect(), cursor(), execute(), fetchone(), fetchall(), rowcount, commit() and parameterised queries.

Steps#

  1. Install and import the connector: pip install mysql-connector-python, then import mysql.connector.
  2. Create a connection with connect().
  3. Create a cursor - an object that runs queries and holds results.
  4. Run SQL with execute().
  5. Read results with fetchone(), fetchmany(n) or fetchall(); cursor.rowcount gives the number of rows.
  6. For INSERT/UPDATE/DELETE call commit() to save changes.
  7. Close the connection.
हिंदी में समझें

पायथन को MySQL से जोड़ने के लिए mysql.connector मॉड्यूल का उपयोग होता है। connect() से संयोजन बनाते हैं, cursor() से कर्सर, execute() से क्वेरी चलाते हैं और बदलाव स्थायी करने के लिए commit() आवश्यक है।

Reading data#

import mysql.connector as sqltor

con = sqltor.connect(host="localhost", user="root",
                     passwd="your_password", database="school")
if con.is_connected():
    print("Connected")

cur = con.cursor()
cur.execute("SELECT roll, name, marks FROM student WHERE marks > 75")
rows = cur.fetchall()            # list of tuples
for r in rows:
    print(r)
print("Rows:", cur.rowcount)
con.close()

Inserting with a parameterised query#

cur = con.cursor()
q = "INSERT INTO student (roll, name, marks) VALUES (%s, %s, %s)"
cur.execute(q, (21, "Kavya", 88))     # values passed separately - safe from SQL injection
con.commit()                          # save the change

String formatting is also asked in exams: "... WHERE marks > {}".format(m) or "... %s" % (m,).

Common Mistake

Without commit(), inserts, updates and deletes are not saved in the database.

Try the idea here (SQLite, built into Python)#

The same cursor pattern works with Python's built-in sqlite3, so you can practise in the browser:

▶ Try it YourselfPython
Ctrl + Enter to run

Exam tips#

  • Fill-in-the-blanks on connect, cursor, execute, fetchall, commit are common.
  • fetchone() returns one tuple (or None); fetchall() returns a list of tuples.

Quick Quiz

Q1.

Method that saves changes made by INSERT/UPDATE is

Q2.

fetchall() returns

Q3.

The object used to execute queries is the

Q4.

Number of rows affected/fetched is given by

Q5.

Placeholder used by mysql.connector in parameterised queries is