Insert Row into MySQL using Python

This blog article shows you how to Insert Row into MySQL using Python.

This Python script below defines a function to insert a new actor record into a MySQL database. Here’s a detailed explanation:

  1. Imports:
  2. Function Definition:
  3. Try Block:
    • try: Starts a try block to handle potential exceptions.
  4. Database Connection:
  5. Cursor and Query Execution:
  6. Exception Handling:
  7. Finally Block:
  8. Example Usage:

from mysql.connector import Error
from datetime import datetime
import mysql.connector
def insert_actor(actor_id, first_name, last_name):
     try:
         connection = mysql.connector.connect(
             host=’localhost’,
             database=’Sakila’,
             user=’root’,
             password=’password’
         )
         if connection.is_connected():
             cursor = connection.cursor()
             insert_query = “””INSERT INTO actor (actor_id, first_name, last_name, last_update)
                               VALUES (%s, %s, %s, %s)”””
             current_time = datetime.now()
             record = (actor_id, first_name, last_name, current_time)
             cursor.execute(insert_query, record)
             connection.commit()
             print(“Record inserted successfully into actor table”)
     except Error as e:
         print(“Error while connecting to MySQL”, e)
     finally:
         if connection.is_connected():
             cursor.close()
             connection.close()
             print(“MySQL connection is closed”)

# Example usage

insert_actor(201, ‘John’, ‘Doe’)

Also: Read image file from Varchar field in MySQL database Python

clip_image002

Source code download: https://github.com/chanmmn/python/tree/main/2024/MySqlInsertActor?WT.mc_id=DP-MVP-36769

Reference: https://dev.mysql.com/doc/connector-python/en/?WT.mc_id=DP-MVP-36769

Unknown's avatar

About chanmingman

Since March 2011 Microsoft Live Spaces migrated to Wordpress (http://www.pcworld.com/article/206455/Microsoft_Live_Spaces_Moves_to_WordPress_An_FAQ.html) till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years. Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in .Net, Cloud, Community, Computers and Internet, Data Platform, programming and tagged . Bookmark the permalink.

1 Response to Insert Row into MySQL using Python

  1. Pingback: MySQL Case in Select Statement | Chanmingman's Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.