जब किसी Python Application में Data को लंबे समय तक सुरक्षित रखना हो, तब केवल Variables या Lists में Data रखना पर्याप्त नहीं होता। ऐसे में Database का उपयोग किया जाता है।
उदाहरण के लिए किसी Student Management System में हमें विद्यार्थियों का—
- नाम
- Roll Number
- मोबाइल नंबर
- Course
- Marks
जैसा Data Store करना पड़ सकता है।
Python में Database के साथ काम करने के लिए अलग-अलग Database Systems का उपयोग किया जा सकता है। शुरुआती स्तर पर SQLite सबसे आसान विकल्पों में से एक है।
Python में SQLite के लिए पहले से उपलब्ध sqlite3 Module का उपयोग किया जाता है।
import sqlite3
Database एक व्यवस्थित स्थान है जहाँ Data को Store, Manage, Search और Update किया जा सकता है।
उदाहरण:
Student Database
Roll No. | Name | Course | Marks
---------|--------|--------|------
101 | Rahul | Python | 85
102 | Amit | Python | 78
103 | Neha | Python | 92
DBMS का पूरा नाम Database Management System है।
यह Database को Create, Store, Update, Delete और Manage करने के लिए उपयोग किया जाता है।
उदाहरण:
- MySQL
- PostgreSQL
- Oracle Database
- Microsoft SQL Server
- SQLite
SQLite एक Lightweight और Serverless Relational Database System है।
इसमें अलग Database Server चलाने की आवश्यकता नहीं होती। Database सामान्यतः एक File में Store किया जा सकता है।
Python में SQLite के लिए:
import sqlite3
का उपयोग किया जाता है।
- Lightweight
- Serverless
- अलग Database Server की आवश्यकता नहीं
- Single Database File में Data Store कर सकता है
- Small और Medium Applications के लिए उपयोगी
- Python में sqlite3 Module उपलब्ध है
- सीखने और Testing के लिए आसान
Python में SQLite Database से Connect करना
import sqlite3
connection = sqlite3.connect("student.db")
print("Database connected")
यदि student.db मौजूद नहीं है, तो SQLite सामान्यतः उसे Create कर सकता है।
Database के साथ Communication शुरू करने के लिए Connection बनाया जाता है।
connection = sqlite3.connect("student.db")
यहाँ connection Database Connection Object है।
Database में SQL Commands Execute करने के लिए Cursor का उपयोग किया जाता है।
cursor = connection.cursor()
अब SQL Query Execute की जा सकती है।
cursor.execute("SELECT * FROM students")
Database Connection का Basic Structure
import sqlite3
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
# SQL Query यहाँ लिखें
connection.commit()
connection.close()
SQL का पूरा नाम Structured Query Language है।
Database में Data के साथ काम करने के लिए SQL का उपयोग किया जाता है।
मुख्य SQL Commands:
- CREATE
- INSERT
- SELECT
- UPDATE
- DELETE
Database के चार मुख्य Operations को CRUD कहा जाता है।
|
CRUD |
अर्थ |
SQL |
|
C |
Create |
INSERT |
|
R |
Read |
SELECT |
|
U |
Update |
UPDATE |
|
D |
Delete |
DELETE |
import sqlite3
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
course TEXT,
marks REAL
)
""")
connection.commit()
connection.close()
यहाँ students नाम की Table बनाई गई है।
हमारी Table में:
|
Column |
Data Type |
उपयोग |
|
id |
INTEGER |
Unique ID |
|
name |
TEXT |
Student Name |
|
age |
INTEGER |
Age |
|
course |
TEXT |
Course |
|
marks |
REAL |
Marks |
PRIMARY KEY किसी Record की Unique पहचान के लिए उपयोग होती है।
id INTEGER PRIMARY KEY
एक Table में Primary Key की Value सामान्यतः Unique होती है।
id INTEGER PRIMARY KEY AUTOINCREMENT
इससे SQLite नए Records के लिए ID Automatically Generate कर सकता है।
उदाहरण:
1
2
3
4
5
import sqlite3
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("""
INSERT INTO students (name, age, course, marks)
VALUES (?, ?, ?, ?)
""", ("Rahul", 20, "Python", 85))
connection.commit()
connection.close()
SQL Query में User Input को सीधे String में जोड़ने के बजाय Parameterized Query का उपयोग करना अधिक सुरक्षित है।
cursor.execute(
"INSERT INTO students (name, age) VALUES (?, ?)",
("Rahul", 20)
)
यह SQL Injection जैसे जोखिमों को कम करने में मदद करता है।
import sqlite3
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
students = [
("Rahul", 20, "Python", 85),
("Amit", 21, "Python", 78),
("Neha", 19, "Python", 92)
]
cursor.executemany("""
INSERT INTO students (name, age, course, marks)
VALUES (?, ?, ?, ?)
""", students)
connection.commit()
connection.close()
execute() और executemany() में अंतर
|
execute() |
executemany() |
|
एक SQL Operation |
कई Records पर समान Operation |
|
Single/individual execution |
Multiple Parameter Sets |
import sqlite3
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
connection.close()
fetchall() Query से प्राप्त सभी Rows को Return करता है।
rows = cursor.fetchall()
केवल एक Row प्राप्त करने के लिए:
cursor.execute("SELECT * FROM students")
row = cursor.fetchone()
print(row)
कुछ Rows प्राप्त करने के लिए:
cursor.execute("SELECT * FROM students")
rows = cursor.fetchmany(2)
print(rows)
cursor.execute("SELECT name, marks FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
किसी विशेष Condition के आधार पर Data प्राप्त करने के लिए WHERE उपयोग होता है।
cursor.execute(
"SELECT * FROM students WHERE marks > ?",
(80,)
)
rows = cursor.fetchall()
for row in rows:
print(row)
name = input("Enter student name: ")
cursor.execute(
"SELECT * FROM students WHERE name = ?",
(name,)
)
student = cursor.fetchone()
if student:
print(student)
else:
print("Student not found")
मान लीजिए Rahul के Marks Update करने हैं:
cursor.execute(
"UPDATE students SET marks = ? WHERE name = ?",
(95, "Rahul")
)
connection.commit()
cursor.execute(
"DELETE FROM students WHERE name = ?",
("Rahul",)
)
connection.commit()
cursor.execute("DELETE FROM students")
connection.commit()
ध्यान दें: यह Table के सभी Records Delete कर देगा। इसलिए इसका उपयोग सावधानी से करना चाहिए।
cursor.execute("DROP TABLE students")
connection.commit()
DROP TABLE पूरी Table को Delete कर देता है।
Database में किए गए Changes को Save करने के लिए:
connection.commit()
का उपयोग किया जाता है।
विशेषकर INSERT, UPDATE और DELETE के बाद Commit करना आवश्यक होता है।
Database Connection बंद करने के लिए:
connection.close()
का उपयोग किया जाता है।
Complete Student Database Program
import sqlite3
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
course TEXT,
marks REAL
)
""")
name = input("Enter Name: ")
age = int(input("Enter Age: "))
course = input("Enter Course: ")
marks = float(input("Enter Marks: "))
cursor.execute("""
INSERT INTO students (name, age, course, marks)
VALUES (?, ?, ?, ?)
""", (name, age, course, marks))
connection.commit()
print("Student added successfully")
cursor.execute("SELECT * FROM students")
for student in cursor.fetchall():
print(student)
connection.close()
Student Management Menu Program
अब एक Basic Menu-Driven Program बनाते हैं।
import sqlite3
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
course TEXT,
marks REAL
)
""")
connection.commit()
while True:
print("\n--- Student Management System ---")
print("1. Add Student")
print("2. View Students")
print("3. Search Student")
print("4. Update Marks")
print("5. Delete Student")
print("6. Exit")
choice = input("Enter Choice: ")
if choice == "1":
name = input("Name: ")
age = int(input("Age: "))
course = input("Course: ")
marks = float(input("Marks: "))
cursor.execute("""
INSERT INTO students (name, age, course, marks)
VALUES (?, ?, ?, ?)
""", (name, age, course, marks))
connection.commit()
print("Student Added Successfully")
elif choice == "2":
cursor.execute("SELECT * FROM students")
students = cursor.fetchall()
for student in students:
print(student)
elif choice == "3":
name = input("Enter Name: ")
cursor.execute(
"SELECT * FROM students WHERE name = ?",
(name,)
)
student = cursor.fetchone()
if student:
print(student)
else:
print("Student Not Found")
elif choice == "4":
student_id = int(input("Enter Student ID: "))
marks = float(input("Enter New Marks: "))
cursor.execute(
"UPDATE students SET marks = ? WHERE id = ?",
(marks, student_id)
)
connection.commit()
print("Marks Updated")
elif choice == "5":
student_id = int(input("Enter Student ID: "))
cursor.execute(
"DELETE FROM students WHERE id = ?",
(student_id,)
)
connection.commit()
print("Student Deleted")
elif choice == "6":
connection.close()
print("Program Closed")
break
else:
print("Invalid Choice")
Marks के अनुसार Data को Sort करने के लिए:
cursor.execute(
"SELECT * FROM students ORDER BY marks DESC"
)
DESC का अर्थ Descending Order है।
Ascending के लिए:
cursor.execute(
"SELECT * FROM students ORDER BY marks ASC"
)
cursor.execute(
"SELECT * FROM students ORDER BY marks DESC LIMIT 1"
)
student = cursor.fetchone()
print(student)
cursor.execute("SELECT COUNT(*) FROM students")
count = cursor.fetchone()[0]
print("Total Students:", count)
cursor.execute("SELECT AVG(marks) FROM students")
average = cursor.fetchone()[0]
print("Average Marks:", average)
cursor.execute("SELECT MAX(marks), MIN(marks) FROM students")
result = cursor.fetchone()
print("Maximum:", result[0])
print("Minimum:", result[1])
Database Operations में Errors आ सकती हैं। उन्हें Handle करने के लिए try-except उपयोग किया जा सकता है।
import sqlite3
try:
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM students")
print(cursor.fetchall())
except sqlite3.Error as error:
print("Database Error:", error)
finally:
if connection:
connection.close()
Database Connection को Manage करने के लिए Context Manager का भी उपयोग किया जा सकता है।
import sqlite3
with sqlite3.connect("student.db") as connection:
cursor = connection.cursor()
cursor.execute(
"SELECT * FROM students"
)
for row in cursor.fetchall():
print(row)
Python Database Connectivity का Flow
Python Program
↓
sqlite3 Module
↓
Database Connection
↓
Cursor
↓
SQL Query
↓
Database
↓
Result
|
Command |
उपयोग |
|
CREATE TABLE |
Table बनाना |
|
INSERT |
Data जोड़ना |
|
SELECT |
Data पढ़ना |
|
UPDATE |
Data बदलना |
|
DELETE |
Data हटाना |
|
DROP TABLE |
Table हटाना |
परीक्षा की दृष्टि से महत्वपूर्ण तथ्य
- Python में SQLite के लिए sqlite3 Module उपयोग होता है।
- SQLite एक Lightweight और Serverless Database System है।
- sqlite3.connect() Database Connection बनाता है।
- cursor() Cursor Object बनाता है।
- execute() SQL Query Execute करता है।
- executemany() Multiple Parameter Sets के साथ Query Execute कर सकता है।
- commit() Database Changes Save करता है।
- close() Connection बंद करता है।
- fetchone() एक Row प्राप्त करता है।
- fetchall() सभी उपलब्ध Rows प्राप्त करता है।
- fetchmany() निर्धारित संख्या में Rows प्राप्त कर सकता है।
- INSERT Data जोड़ने के लिए।
- SELECT Data पढ़ने के लिए।
- UPDATE Data बदलने के लिए।
- DELETE Data हटाने के लिए।
- PRIMARY KEY Record की Unique पहचान के लिए उपयोगी है।
- AUTOINCREMENT ID को Automatically बढ़ाने में उपयोगी है।
- Parameterized Queries SQL Injection के जोखिम को कम करने में मदद करती हैं।
प्रश्न 1. Python में SQLite के लिए कौन-सा Module है?
sqlite3
प्रश्न 2. Database से Connect कैसे करें?
sqlite3.connect("database.db")
प्रश्न 3. SQL Query Execute करने के लिए?
cursor.execute()
प्रश्न 4. सभी Records प्राप्त करने के लिए?
fetchall()
प्रश्न 5. एक Record प्राप्त करने के लिए?
fetchone()
प्रश्न 6. Database Changes Save करने के लिए?
commit()
प्रश्न 7. Database Connection बंद करने के लिए?
close()
प्रश्न 8. Data जोड़ने के लिए कौन-सी SQL Command है?
INSERT
SELECT
प्रश्न 10. Data Update करने के लिए?
UPDATE
प्रश्न 11. Data Delete करने के लिए?
DELETE
- Database → Data Store करने की व्यवस्थित जगह
- DBMS → Database Management System
- SQLite → Lightweight, Serverless Database
- sqlite3 → Python SQLite Module
- connect() → Database Connection
- cursor() → SQL Execution के लिए Cursor
- execute() → SQL Query Execute
- commit() → Changes Save
- fetchone() → One Row
- fetchall() → All Rows
- INSERT → Add
- SELECT → Read
- UPDATE → Modify
- DELETE → Remove
- CRUD → Create, Read, Update, Delete
अगला अध्याय —Python Exception Handling
इसमें Error और Exception में अंतर, try, except, else, finally, raise, Multiple Exceptions, Custom Exceptions और Practical Programs विस्तार से होंगे।