Inserting data into a new column of an existing table using Python
Altering table structure to add a new column and populating it with values via Python.
import mysql.connector
conn = mysql.connector.connect(
host='localhost', user='root', password='password', database='company_db'
)
cursor = conn.cursor()
# Step 1: Add new column
cursor.execute("ALTER TABLE employees ADD COLUMN department_code VARCHAR(10) DEFAULT 'ENG'")
# Step 2: Update column values
cursor.execute("UPDATE employees SET department_code = %s WHERE employee_id = %s", ('HR', 2))
conn.commit()
print("New column added and populated successfully!")
conn.close()New column added and populated successfully!