Steps#
- Install and import the connector:
pip install mysql-connector-python, thenimport mysql.connector. - Create a connection with
connect(). - Create a cursor - an object that runs queries and holds results.
- Run SQL with
execute(). - Read results with
fetchone(),fetchmany(n)orfetchall();cursor.rowcountgives the number of rows. - For INSERT/UPDATE/DELETE call
commit()to save changes. - 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,).
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:
Exam tips#
- Fill-in-the-blanks on
connect,cursor,execute,fetchall,commitare common. fetchone()returns one tuple (or None);fetchall()returns a list of tuples.