Wednesday, July 3, 2024
HomeLanguagesPythonAdding new enum column to an existing MySQL table using Python

Adding new enum column to an existing MySQL table using Python

Prerequisite: Python: MySQL Create Table

In this article, we are going to see how to add a new enum column to an existing MySQL table using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. 

Database table in use:

We are going to use Lazyroar(Database name) database and table describing the salary.

Approach:

  • Import module.
  • Make a connection request with the database.
  • Create an object for the database cursor.
  • Execute the following MySQL query:
ALTER TABLE table_name ADD colunm_name  ENUM('field1','field2',...)
  • And print the result.

Below is the implementation with python:

Python3




# Establish connection to MySQL database
import mysql.connector
  
db = mysql.connector.connect(
  host = "localhost",
  user = "root",
  password = "rot23",
  database = "Lazyroar"
  )
  
# getting the cursor by cursor() method
mycursor = db.cursor()
  
query = "ALTER TABLE store ADD Department  ENUM('Sweet','Snaks');"
  
mycursor.execute(query)
  
mycursor.execute(" desc store;"
myresult = mycursor.fetchall() 
for row in myresult: 
    print(row)
      
db.commit() 
  
# close the Connection
db.close()


Output:

Let’s check on SQL shell:

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments