Delete a Column in Table in Python MySQL

Python MySQL – Delete a column in table

To delete a column in MySQL table from a Python program,

  1. Create a connection to the MySQL database with user credentials and database name, using connect() function.
  2. Get cursor object to the database using cursor() function.
  3. Call execute() function on the cursor object, and pass the ALTER table query with the specific column name. The ALTER query removes the specified column in the table.

Example

Consider that there is a schema named mydatabase in MySQL. The credentials to access this database are: user – root and password – admin1234, and there is a table named fruits in mydatabase.

In the following program, we remove the country column in fruits table using ALTER query.

Python Program

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="admin1234",
  database="mydatabase"
)

mycursor = mydb.cursor()

try:
  mycursor.execute("ALTER TABLE fruits DROP COLUMN country")
  print('Column deleted successfully.')
except:
  print('An exception occurred during column delete operation.')

mydb.commit()

Output

Column deleted successfully.

Table data after ALTER operation

Python MySQL - Delete a column in table

Summary

In this tutorial of Python Examples, we learned how to delete a column in MySQL table, from a Python program.