← Back to Python Course | Chapter 15: Python & MySQL | Lesson 1 of 12

Python MySQL Get Started

Python सीधे out of the box MySQL database से बात नहीं करता -- पहले एक अलग driver package install करना पड़ता है, सबसे आम तौर पर mysql-connector-python। एक बार install हो जाने के बाद, किसी Python script से connect करना एक सरल, consistent pattern follow करता है: connector import करें, अपनी credentials से एक connection खोलें, और आप queries चलाने के लिए तैयार हैं।
Syntax
python
import mysql.connector

connection = mysql.connector.connect(
    host="host", user="user", password="password"
)

MySQL Connector Install करना

pip install mysql-connector-python official MySQL driver package download और install करता है, जिससे आपकी scripts में import करने के लिए mysql.connector module उपलब्ध हो जाता है -- यह आप जिस भी Python environment (या virtual environment) में काम कर रहे हैं, उसमें एक बार का setup step है।

Note: इस package को globally नहीं, बल्कि अपने project के लिए specific एक virtual environment के अंदर install करें, ताकि आपके project की dependencies isolated और reproducible रहें।
Warning: यह installation step भूलकर सीधे mysql.connector import करने की कोशिश करना ModuleNotFoundError देता है, जो शुरुआती लोगों के लिए सबसे आम पहली रुकावट है।

उदाहरण: Installing the MySQL Connector

python
# pip install mysql-connector-python
print("Installs the mysql.connector module for your Python environment")

एक Basic Connection बनाना

mysql.connector.connect(host="localhost", user="root", password="", database="mydatabase") दी गई credentials से MySQL server से एक connection खोलता है, और हर आगे की query के लिए इस्तेमाल होने वाला एक connection object return करता है।

Note: जब आपकी Python script और MySQL server एक ही machine पर चल रहे हों, तो host के रूप में "localhost" इस्तेमाल करें, यह सबसे आम local development setup है।
Warning: गलत username, password, host, या database name एक connection failure देता है, जिसे explicitly check और handle किया जाना चाहिए, यह मान लेने की बजाय कि हमेशा succeed होगा।

उदाहरण: Establishing a Basic Connection

python
from unittest.mock import MagicMock

# Stands in for mysql.connector.connect(), which needs a real MySQL server
connect = MagicMock(return_value=MagicMock())
conn = connect(host="localhost", user="root", password="", database="mydatabase")
print(type(conn))

Connection Errors को Handle करना

mysql.connector.Error वह base exception class है जो connection attempt fail होने पर raise होती है -- इसे try-except block में catch करने से आप एक साफ error message दिखा सकते हैं और gracefully fail हो सकते हैं, बजाय इसके कि किसी unhandled exception से script crash हो जाए।

Note: किसी भी real script की शुरुआत से ही अपने connection attempt को try-except block में wrap करें, और connection failures को साफ-सुथरे तरीके से handle करने के लिए specifically mysql.connector.Error catch करें।
Warning: Connection error को बिना handle किए आगे बढ़ने देना एक raw traceback देता है, जो बिना Python debugging experience वाले किसी भी व्यक्ति के लिए script चलाते समय confusing हो सकता है।

उदाहरण: Handling Connection Errors

python
from unittest.mock import MagicMock

class Error(Exception):
    pass

# Stands in for mysql.connector.connect() failing with mysql.connector.Error
connect = MagicMock(side_effect=Error("Access denied"))
try:
    connect(host="localhost", user="root", password="wrong")
except Error as e:
    print("Connection failed:", e)

Credentials को Securely Store करना

Database credentials को कभी भी सीधे किसी ऐसी script में hardcode नहीं करना चाहिए जो version control में commit होती है -- उन्हें environment variables से (os.environ या python-dotenv package इस्तेमाल करके) load करना sensitive values को आपके codebase की history से पूरी तरह बाहर रखता है।

Note: अपने committed code के बाहर credentials रखने के लिए एक .env file (python-dotenv से load की गई) या अपने hosting platform की environment variable settings इस्तेमाल करें।
Warning: Version control में commit हुई credentials उस history में हमेशा के लिए रह जाती हैं, भले ही किसी बाद के commit में हटा दी जाएँ -- गलती से commit हुई किसी भी credential को compromised मानें और उसे rotate करें।

उदाहरण: Storing Credentials Securely

python
import os
db_user = os.environ.get("DB_USER", "root")  # read from the environment, not hardcoded
db_password = os.environ.get("DB_PASSWORD", "")
print("Loaded credentials from environment, not hardcoded")

एक Connection को Close करना

conn.close() किसी database connection की ज़रूरत खत्म होने पर उसे explicitly close कर देता है, जिससे Python side और MySQL server दोनों पर resource free हो जाता है -- यह लंबे समय तक चलने वाली scripts या कई short-lived connections खोलने वाली scripts में खासकर महत्वपूर्ण है।

Note: जो भी connection खोलें उसे close ज़रूर करें, आदर्श रूप से try/finally block (या with statement, अगर आपका driver version support करता है) इस्तेमाल करके, ताकि error आने पर भी वह close होना guarantee हो।
Warning: Connections को खोलकर close न करना, खासकर बार-बार चलने वाली या कई connections खोलने वाली script में, समय के साथ MySQL server की उपलब्ध connection limit को खत्म कर सकता है।

उदाहरण: Closing a Connection

python
from unittest.mock import MagicMock

connect = MagicMock(return_value=MagicMock())
conn = connect(host="localhost")
conn.close()  # releases the connection when it's no longer needed
print("Connection closed")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.