🗄️ Unit 3 – Database और SQL · Lesson 24
Python–MySQL Connectivity
Python को MySQL से क्यों जोड़ें?
असली applications – school ERP, railway booking, shopping apps – में program front end और database back end होता है। Python MySQL को SQL भेजकर results इस्तेमाल कर सकता है।
Connector install करना
Command prompt
pip install mysql-connector-python
फिर import mysql.connector (अक्सर mc नाम से) करें। connect() में अपना MySQL user name और password लिखें।
Database program के steps
- 1import mysql.connector
- 2con = connect(host, user, passwd, database)
- 3cur = con.cursor()
- 4cur.execute("SQL query")
- 5SELECT → fetchall()/fetchone(); बदलाव → con.commit()
- 6con.close()
Connect करके table बनाना
Python
import mysql.connector as mc
con = mc.connect(host='localhost', user='root', passwd='root123')
if con.is_connected():
print('Connected to MySQL')
cur = con.cursor()
cur.execute('CREATE DATABASE IF NOT EXISTS school')
cur.execute('USE school')
cur.execute('DROP TABLE IF EXISTS student')
cur.execute('''CREATE TABLE student (
roll INT PRIMARY KEY, name VARCHAR(20),
stream VARCHAR(10), marks INT)''')
print('Table created')
con.close()Connected to MySQL
Table created
Records insert और commit()
Python
import mysql.connector as mc
con = mc.connect(host='localhost', user='root', passwd='root123', database='school')
cur = con.cursor()
rows = [(1, 'Anika', 'Science', 92), (2, 'Dev', 'Commerce', 78),
(3, 'Farhan', 'Science', 64), (4, 'Gauri', 'Arts', 88)]
for r in rows:
q = "INSERT INTO student VALUES ({}, '{}', '{}', {})".format(*r)
cur.execute(q)
con.commit() # save changes permanently
print(len(rows), 'records inserted')
con.close()4 records inserted
Results fetch करना
Python
import mysql.connector as mc
con = mc.connect(host='localhost', user='root', passwd='root123', database='school')
cur = con.cursor()
cur.execute('SELECT * FROM student')
data = cur.fetchall() # list of tuples
print('Rows fetched:', cur.rowcount)
for roll, name, stream, marks in data:
print(roll, name.ljust(7), stream.ljust(9), marks)
con.close()Rows fetched: 4
1 Anika Science 92
2 Dev Commerce 78
3 Farhan Science 64
4 Gauri Arts 88
Python
import mysql.connector as mc
con = mc.connect(host='localhost', user='root', passwd='root123', database='school')
cur = con.cursor()
cur.execute('SELECT name, marks FROM student ORDER BY marks DESC')
print('fetchone :', cur.fetchone())
print('fetchmany:', cur.fetchmany(2))
print('rest :', cur.fetchall())
print('rowcount :', cur.rowcount) # rows read so far
con.close()fetchone : ('Anika', 92)
fetchmany: [('Gauri', 88), ('Dev', 78)]
rest : [('Farhan', 64)]
rowcount : 4
User input वाली queries (%s)
Values को %s placeholders से अलग भेजें – connector सही quotes लगाता है और SQL injection से बचाता है। ऊपर वाला format() / f-string तरीका भी board papers में आता है।
Python
import mysql.connector as mc
con = mc.connect(host='localhost', user='root', passwd='root123', database='school')
cur = con.cursor()
stream = input('Stream to search: ')
cur.execute('SELECT roll, name, marks FROM student WHERE stream = %s', (stream,))
for row in cur.fetchall():
print(row)
con.close()Stream to search: Science
(1, 'Anika', 92)
(3, 'Farhan', 64)
UPDATE और DELETE
Python
import mysql.connector as mc
con = mc.connect(host='localhost', user='root', passwd='root123', database='school')
cur = con.cursor()
roll = int(input('Roll to update: '))
new = int(input('New marks: '))
cur.execute('UPDATE student SET marks = %s WHERE roll = %s', (new, roll))
con.commit()
print(cur.rowcount, 'row(s) updated')
cur.execute('SELECT * FROM student WHERE roll = %s', (roll,))
print(cur.fetchone())
con.close()Roll to update: 3
New marks: 70
1 row(s) updated
(3, 'Farhan', 'Science', 70)
Python
import mysql.connector as mc
con = mc.connect(host='localhost', user='root', passwd='root123', database='school')
cur = con.cursor()
cur.execute('DELETE FROM student WHERE marks < %s', (75,))
con.commit()
print('Deleted:', cur.rowcount)
cur.execute('SELECT COUNT(*), AVG(marks) FROM student')
cnt, avg = cur.fetchone()
print('Left:', cnt, '| average:', round(float(avg), 2))
con.close()Deleted: 1
Left: 3 | average: 86.0
Error handling के साथ पूरा program
Python
import mysql.connector as mc
def connect():
return mc.connect(host='localhost', user='root', passwd='root123', database='school')
def add(roll, name, stream, marks):
con = connect(); cur = con.cursor()
try:
cur.execute('INSERT INTO student VALUES (%s, %s, %s, %s)', (roll, name, stream, marks))
con.commit(); print('Added', name)
except mc.Error as e:
print('Error:', e.msg)
con.close()
def show():
con = connect(); cur = con.cursor()
cur.execute('SELECT * FROM student ORDER BY roll')
for r in cur.fetchall():
print(r)
con.close()
add(5, 'Harsh', 'Commerce', 81)
add(1, 'Copy', 'Arts', 50) # duplicate primary key
show()Added Harsh
Error: Duplicate entry '1' for key 'PRIMARY'
(1, 'Anika', 'Science', 92)
(2, 'Dev', 'Commerce', 78)
(4, 'Gauri', 'Arts', 88)
(5, 'Harsh', 'Commerce', 81)
Methods का सारांश
| Method / attribute | Purpose |
|---|---|
| mysql.connector.connect(host, user, passwd, database) | Open a connection |
| con.is_connected() | True if connected |
| con.cursor() | Create a cursor to run queries |
| cur.execute(query, params) | Run one SQL statement |
| con.commit() | Save INSERT/UPDATE/DELETE |
| cur.fetchone() / fetchmany(n) / fetchall() | Read result rows |
| cur.rowcount | Rows fetched / affected |
| con.close() | Close the connection |
अक्सर पूछे जाने वाले प्रश्न (FAQ)
commit() क्यों ज़रूरी है?
INSERT, UPDATE और DELETE एक transaction में रहते हैं। commit() उन्हें हमेशा के लिए save करता है; इसके बिना connection बंद होने पर changes खो जाते हैं।
fetchone(), fetchmany() और fetchall() में क्या फ़र्क है?
fetchone() अगली row tuple के रूप में (या None) देता है, fetchmany(n) अगली n rows की list, और fetchall() बची हुई सभी rows की list देता है।
rowcount क्या देता है?
SELECT के लिए अब तक fetch हुई rows की संख्या; INSERT/UPDATE/DELETE के लिए प्रभावित rows की संख्या।
