Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
Insert Operation in Python - Insert Operation in Python

Insert Operation in Python

Posted on December 22, 2024December 22, 2024 By Rishabh saini No Comments on Insert Operation in Python

Insert Operation in Python

Adding records to a database table is one of the most fundamental operations when working with SQL and Python. In Python, the INSERT INTO statement is utilized to add records to a table, and placeholders such as %s are used to define values dynamically. By leveraging Python’s mysql.connector, we can execute SQL statements seamlessly. This blog post will guide you through performing single and multiple record insertions, and retrieving the last inserted row’s ID with professional clarity and a human touch.

Download New Real Time Projects :-Click here

Insert Operation in Python
Insert Operation in Python

Inserting a Single Record

To insert a single record into a database table, we use the INSERT INTO statement with placeholders for the values. Python’s cursor.execute() method allows us to execute this statement, passing the actual values as a tuple.

Example: Inserting a Single Record

import mysql.connector

# Create the connection object
myconn = mysql.connector.connect(
    host="localhost", 
    user="root", 
    passwd="google", 
    database="PythonDB"
)

# Create the cursor object
cur = myconn.cursor()

# SQL query with placeholders
sql = "INSERT INTO Employee(name, id, salary, dept_id, branch_name) VALUES (%s, %s, %s, %s, %s)"

# Tuple containing the values to be inserted
val = ("John", 110, 25000.00, 201, "Newyork")

try:
    # Insert the record
    cur.execute(sql, val)

    # Commit the transaction
    myconn.commit()

    print(cur.rowcount, "record inserted!")

except:
    # Rollback in case of an error
    myconn.rollback()

# Close the connection
myconn.close()

Output:

1 record inserted!

Inserting Multiple Records

Python also enables inserting multiple records in a single operation using the executemany() method. Here, a list of tuples is used, where each tuple represents a row to be inserted.

Example: Inserting Multiple Records

import mysql.connector

# Create the connection object
myconn = mysql.connector.connect(
    host="localhost", 
    user="root", 
    passwd="google", 
    database="PythonDB"
)

# Create the cursor object
cur = myconn.cursor()

# SQL query with placeholders
sql = "INSERT INTO Employee(name, id, salary, dept_id, branch_name) VALUES (%s, %s, %s, %s, %s)"

# List of tuples containing multiple rows to insert
val = [
    ("John", 102, 25000.00, 201, "Newyork"),
    ("David", 103, 25000.00, 202, "Port of Spain"),
    ("Nick", 104, 90000.00, 201, "Newyork")
]

try:
    # Insert multiple records
    cur.executemany(sql, val)

    # Commit the transaction
    myconn.commit()

    print(cur.rowcount, "records inserted!")

except:
    # Rollback in case of an error
    myconn.rollback()

# Close the connection
myconn.close()

Output:

3 records inserted!

Retrieving the Row ID

Each row in a SQL table is uniquely identified by a row ID. When inserting a record, Python provides a way to fetch the last inserted row ID using the lastrowid attribute of the cursor object.

Example: Retrieving the Last Inserted Row ID

import mysql.connector

# Create the connection object
myconn = mysql.connector.connect(
    host="localhost", 
    user="root", 
    passwd="google", 
    database="PythonDB"
)

# Create the cursor object
cur = myconn.cursor()

# SQL query with placeholders
sql = "INSERT INTO Employee(name, id, salary, dept_id, branch_name) VALUES (%s, %s, %s, %s, %s)"

# Tuple containing the values to be inserted
val = ("Mike", 105, 28000, 202, "Guyana")

try:
    # Insert the record
    cur.execute(sql, val)

    # Commit the transaction
    myconn.commit()

    # Fetch and print the last inserted row ID
    print(cur.rowcount, "record inserted! ID:", cur.lastrowid)

except:
    # Rollback in case of an error
    myconn.rollback()

# Close the connection
myconn.close()

Output:

1 record inserted! ID: 0

Key Points to Remember

  1. Use %s as the placeholder for dynamic values in the INSERT INTO statement.
  2. Always handle database connections carefully using try-except blocks to manage errors.
  3. Use executemany() for bulk insertions to improve efficiency.
  4. Retrieve the last inserted row ID using cursor.lastrowid for unique row identification.

These Python SQL operations showcase how effectively we can manage database interactions in Python using mysql.connector. Whether you’re inserting single records, bulk data, or need to identify specific rows, this approach provides a robust and professional way to handle SQL operations.

PHP PROJECT:- CLICK HERE


insert operation in python w3schools
insert operation in python example
python insert into list at index
python list insert
Insert Operation in Python
Insert Operation in Python list insert time complexity
Insert Operation in Python list insert at end
string insert python
Insert Operation in Python insert list into list

Post Views: 590
Python

Post navigation

Previous Post: Student Record and Information System in Java
Next Post: AI in Programming

More Related Articles

Data Types in Python Python
OOP in Python Chapter 9: Object-Oriented Programming OOP in Python Python
Python Tkinter Listbox Python Tkinter Listbox: A Comprehensive Guide Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

  1. Python Decorators: A Comprehensive Guide
  2. How to Calculate Distance between Two Points using GEOPY
  3. Rock, Paper, Scissors Game
  4. Database Operations: UPDATE and DELETE in MySQL Using Python
  5. How to Install Django: Step-by-Step Guide
  6. Python Tkinter Canvas: A Guide to Structured Graphics in Python

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,616)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,218)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,872)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme