Try it here
Subscribe
DML in Python

Mysql DML with Python3

mysql_dml_with_python3

Below are the steps to perform DML operation in Mysql using Python:

  • Install mysql-python using below
    pip install mysql-python
  • Establish a MySQL database connection in Python.
  • Create cursor object.
  • Define the SQL INSERT Query.
  • Execute the INSERT query using the cursor.execute()and get a number of rows affected.
  • After the successful execution of a query, Don’t forget to commit your changes to the database.
  • Close the MySQL database connection.
  • Catch SQL exceptions if any.

Example:

import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='my_db_name',
                                         user='my_user',
                                         password='my_db_pass')
    sql= """INSERT INTO employee(id, Name, dept, join_date) 
                                VALUES (%s, %s, %s, %s) """
    emp_record= (1, 'John', 10, '2020-04-18')
    cursor = connection.cursor()
    cursor.execute(sql,emp_record)
    connection.commit()
    print(cursor.rowcount, "Record inserted successfully into Employee table")
    cursor.close()

except mysql.connector.Error as error:
    print("Failed to insert record into Employee table {}".format(error))

finally:
    if (connection.is_connected()):
        connection.close()
        print("MySQL connection is closed")

Writer profile pic

Devbarma on Apr 18, 2020 at 06:04 am


This article is contributed by Devbarma. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

WEB TECHNOLOGY

Articles

×

Forgot Password

Please enter your email address below and we will send you information to change your password.