Python MySQL Insert Into Table
In this page:
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 के रूप में सुरक्षित तरीके से दी जाती हैं।
उदाहरण: Basic INSERT Statement
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 बंद होने पर खो जाते हैं।
उदाहरण: Committing the Transaction
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 करने के लिए।
उदाहरण: Getting the New Row's ID
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 कर देता है।
उदाहरण: Inserting Multiple Rows at Once
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() करने देता है।
उदाहरण: Handling Insert Errors Gracefully
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)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Python MySQL Get Started
- Python MySQL Create Database
- Python MySQL Create Table
- Python MySQL Insert Into Table
- Python MySQL Select From Table
- Python MySQL Select With a Filter
- Python MySQL Order By
- Python MySQL Delete Record
- Python MySQL Drop Table
- Python MySQL Update Table
- Python MySQL Limit
- Python MySQL Join