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

Python MySQL Insert Into Table

किसी table में नई rows को cursor से execute किए गए INSERT INTO SQL statement से जोड़ा जाता है -- महत्वपूर्ण बात यह है कि actual values के लिए SQL string हाथ से बनाने की बजाय parameterized placeholders (%s) इस्तेमाल किए जाते हैं, जो SQL injection से बचाता है।
Syntax
python
sql = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
cursor.execute(sql, (value1, value2))
connection.commit()

Basic INSERT Statement

cursor.execute("INSERT INTO customers (name, address) VALUES (%s, %s)", (name, address)) customers table में एक नई row जोड़ता है, जहाँ actual values SQL string में सीधे embed करने की बजाय एक अलग tuple argument के रूप में सुरक्षित तरीके से दी जाती हैं।

Note: INSERT statements बनाने के लिए हमेशा %s placeholders को अलग values tuple के साथ इस्तेमाल करें, कभी Python string formatting नहीं -- यह सबसे महत्वपूर्ण MySQL security habit है जिसे बनाना चाहिए।
Warning: SQL string में %s placeholders की संख्या values tuple में items की संख्या से बिल्कुल मेल खानी चाहिए, वरना Python query के MySQL तक पहुँचने से पहले ही एक error raise कर देता है।

उदाहरण: Basic INSERT Statement

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
name, address = "John", "Highway 21"
cursor.execute("INSERT INTO customers (name, address) VALUES (%s, %s)", (name, address))  # values passed safely as a tuple, not embedded in the string
print("Row inserted safely with placeholders")

Transaction को Commit करना

conn.commit(), किसी भी pending INSERT, UPDATE, या DELETE बदलाव को database में permanently save करता है -- इसे call किए बिना, current connection के दौरान किए गए बदलाव असल में persist नहीं होते और connection बंद होने पर खो जाते हैं।

Note: हर INSERT/UPDATE/DELETE operation के तुरंत बाद (या batch में, उनके related समूह के बाद) conn.commit() call करें, यह मान लेने की बजाय कि यह automatically हो जाता है।
Warning: conn.commit() भूल जाना सबसे आम Python-MySQL गलतियों में से एक है -- code बिना किसी error के चलता है, फिर भी data रहस्यमय तरीके से database में कभी दिखता नहीं।

उदाहरण: Committing the Transaction

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute("INSERT INTO customers (name) VALUES (%s)", ("John",))
conn.commit()  # without this, the insert would not be permanently saved
print("Changes permanently saved")

नई Row की ID पाना

cursor.lastrowid सबसे हाल ही insert हुई row की auto-generated primary key value return करता है -- यह तब उपयोगी है जब आपको वह नई ID तुरंत चाहिए हो, उदाहरण के लिए किसी दूसरे table में उसके तुरंत बाद related rows insert करने के लिए।

Note: INSERT और commit के तुरंत बाद, उसी cursor पर कोई और query चलाने से पहले cursor.lastrowid पढ़ें, क्योंकि इसकी value सिर्फ सबसे हाल के insert को दिखाती है।
Warning: cursor.lastrowid तभी meaningful है जब table की primary key एक AUTO_INCREMENT column हो -- manually assign की गई primary keys वाली tables के लिए यह उपयोगी नहीं है।

उदाहरण: Getting the New Row's ID

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.lastrowid = 1
cursor.execute("INSERT INTO customers (name) VALUES (%s)", ("John",))
conn.commit()
print("New customer id:", cursor.lastrowid)  # auto-generated primary key of the row just inserted

एक साथ कई Rows Insert करना

cursor.executemany(sql, list_of_tuples) एक ही call में कई rows insert करता है, जो हर row के लिए अलग-अलग execute() call करते हुए loop चलाने से कहीं ज़्यादा efficient है, क्योंकि यह database server से network round-trips को batch कर देता है।

Note: एक साथ कुछ से ज़्यादा rows insert करते समय हमेशा executemany() इस्तेमाल करें -- individual execute() calls के loop की तुलना में performance का अंतर scale पर काफी बड़ा हो जाता है।
Warning: executemany() को अब भी list के हर tuple में SQL string में %s placeholders जितने ही elements चाहिए होते हैं।

उदाहरण: Inserting Multiple Rows at Once

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
customers = [("Amy", "Apple St"), ("Hannah", "Mountain 21")]
cursor.executemany("INSERT INTO customers (name, address) VALUES (%s, %s)", customers)  # inserts all rows in one batched call
conn.commit()
print(len(customers), "rows inserted in one batch")

Insert Errors को Gracefully Handle करना

किसी INSERT को try-except block में wrap करके mysql.connector.Error catch करना आपको failures -- जैसे कोई unique constraint या foreign key relationship violate होना -- को बिना पूरी script crash किए handle करने देता है, और आपको एक failed, partial transaction discard करने के लिए conn.rollback() करने देता है।

Note: किसी failed insert के except block में conn.rollback() call करें ताकि किसी भी partial बदलाव को साफ तरीके से discard किया जा सके, और database को एक consistent state में रखा जा सके।
Warning: किसी बड़े multi-step transaction के अंदर एक failed INSERT चीज़ों को inconsistent state में छोड़ सकता है अगर आप explicitly rollback न करें -- write operations के लिए हमेशा try/except को rollback के साथ जोड़ें।

उदाहरण: Handling Insert Errors Gracefully

python
from unittest.mock import MagicMock

class Error(Exception):
    pass

conn = MagicMock()
cursor = conn.cursor()
cursor.execute.side_effect = Error("Duplicate entry")
try:
    cursor.execute("INSERT INTO customers (name) VALUES (%s)", ("John",))
    conn.commit()
except Error as e:
    conn.rollback()  # discards the failed, partial transaction
    print("Insert failed, rolled back:", e)
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.