Class 12 Programs

Quick Tips

  • • Import random module for number generation
  • • Use randint(1, 6) for dice simulation
  • • Handle user input validation properly

ALTER TABLE Operations in MySQL

AIM

To write Python programs to demonstrate ALTER TABLE operations in MySQL including adding columns, dropping columns, modifying column data types, and adding constraints.

Key Concepts:

  • ALTER TABLE: SQL command to modify table structure
  • ADD COLUMN: Adding new columns to existing table
  • DROP COLUMN: Removing columns from table
  • MODIFY: Changing column data types and constraints

ALGORITHM

  1. Start
  2. Import mysql.connector module
  3. Establish connection to MySQL database
  4. Create cursor object
  5. Execute ALTER TABLE commands for different operations
  6. Commit the changes
  7. Display table structure to verify changes
  8. Close cursor and connection
  9. Stop

PROGRAM

import mysql.connector

def connect_database():
    """Establish connection to MySQL database"""
    try:
        connection = mysql.connector.connect(
            host='localhost',
            database='school',
            user='root',
            password='password'
        )
        return connection
    except mysql.connector.Error as error:
        print(f"Error connecting to MySQL: {error}")
        return None

def create_sample_table(cursor):
    """Create a sample students table"""
    try:
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS students (
                id INT PRIMARY KEY,
                name VARCHAR(50),
                age INT
            )
        """)
        print("Sample table 'students' created successfully")
    except mysql.connector.Error as error:
        print(f"Error creating table: {error}")

def add_column(cursor):
    """Add new column to table"""
    try:
        # Add email column
        cursor.execute("ALTER TABLE students ADD COLUMN email VARCHAR(100)")
        print("Column 'email' added successfully")
        
        # Add phone column with default value
        cursor.execute("ALTER TABLE students ADD COLUMN phone VARCHAR(15) DEFAULT 'Not Provided'")
        print("Column 'phone' added with default value")
        
    except mysql.connector.Error as error:
        print(f"Error adding column: {error}")

def modify_column(cursor):
    """Modify existing column"""
    try:
        # Modify name column size
        cursor.execute("ALTER TABLE students MODIFY COLUMN name VARCHAR(100)")
        print("Column 'name' size modified to VARCHAR(100)")
        
        # Modify age column to add NOT NULL constraint
        cursor.execute("ALTER TABLE students MODIFY COLUMN age INT NOT NULL")
        print("Column 'age' modified to NOT NULL")
        
    except mysql.connector.Error as error:
        print(f"Error modifying column: {error}")

def drop_column(cursor):
    """Drop column from table"""
    try:
        # Drop phone column
        cursor.execute("ALTER TABLE students DROP COLUMN phone")
        print("Column 'phone' dropped successfully")
        
    except mysql.connector.Error as error:
        print(f"Error dropping column: {error}")

def add_constraint(cursor):
    """Add constraints to table"""
    try:
        # Add unique constraint to email
        cursor.execute("ALTER TABLE students ADD CONSTRAINT unique_email UNIQUE (email)")
        print("UNIQUE constraint added to email column")
        
    except mysql.connector.Error as error:
        print(f"Error adding constraint: {error}")

def show_table_structure(cursor):
    """Display table structure"""
    try:
        cursor.execute("DESCRIBE students")
        result = cursor.fetchall()
        
        print("\nTable Structure:")
        print("-" * 60)
        print(f"{'Field':<15} {'Type':<20} {'Null':<5} {'Key':<5} {'Default':<10}")
        print("-" * 60)
        
        for row in result:
            field, type_info, null, key, default, extra = row
            print(f"{field:<15} {type_info:<20} {null:<5} {key:<5} {str(default):<10}")
            
    except mysql.connector.Error as error:
        print(f"Error showing table structure: {error}")

def main():
    """Main function to demonstrate ALTER TABLE operations"""
    connection = connect_database()
    
    if connection is None:
        return
    
    cursor = connection.cursor()
    
    try:
        print("=== ALTER TABLE Operations Demo ===\n")
        
        # Create sample table
        create_sample_table(cursor)
        
        print("\n1. Initial table structure:")
        show_table_structure(cursor)
        
        # Add columns
        print("\n2. Adding columns...")
        add_column(cursor)
        connection.commit()
        show_table_structure(cursor)
        
        # Modify columns
        print("\n3. Modifying columns...")
        modify_column(cursor)
        connection.commit()
        show_table_structure(cursor)
        
        # Add constraints
        print("\n4. Adding constraints...")
        add_constraint(cursor)
        connection.commit()
        show_table_structure(cursor)
        
        # Drop column
        print("\n5. Dropping column...")
        drop_column(cursor)
        connection.commit()
        show_table_structure(cursor)
        
        print("\n=== All ALTER TABLE operations completed successfully ===")
        
    except mysql.connector.Error as error:
        print(f"Database error: {error}")
        connection.rollback()
    
    finally:
        cursor.close()
        connection.close()
        print("\nDatabase connection closed.")

if __name__ == "__main__":
    main()

OUTPUT

=== ALTER TABLE Operations Demo ===

Sample table 'students' created successfully

1. Initial table structure:

------------------------------------------------------------

Field Type Null Key Default

------------------------------------------------------------

id int NO PRI None

name varchar(50) YES None

age int YES None

2. Adding columns...

Column 'email' added successfully

Column 'phone' added with default value

------------------------------------------------------------

Field Type Null Key Default

------------------------------------------------------------

id int NO PRI None

name varchar(50) YES None

age int YES None

email varchar(100) YES None

phone varchar(15) YES Not Provided

3. Modifying columns...

Column 'name' size modified to VARCHAR(100)

Column 'age' modified to NOT NULL

4. Adding constraints...

UNIQUE constraint added to email column

5. Dropping column...

Column 'phone' dropped successfully

------------------------------------------------------------

Field Type Null Key Default

------------------------------------------------------------

id int NO PRI None

name varchar(100) YES None

age int NO None

email varchar(100) YES UNI None

=== All ALTER TABLE operations completed successfully ===

Database connection closed.

CONCLUSION

The program successfully demonstrates various ALTER TABLE operations in MySQL using Python. It shows how to add columns, modify existing columns, add constraints, and drop columns. The program also includes proper error handling and displays the table structure after each operation to verify the changes.

VIVA QUESTIONS

  1. What is ALTER TABLE command used for?

    ALTER TABLE is used to modify the structure of an existing table, including adding/dropping columns, modifying column data types, and adding/removing constraints.

  2. How do you add a column with a default value?

    Use: ALTER TABLE table_name ADD COLUMN column_name datatype DEFAULT default_value;

  3. What is the difference between MODIFY and CHANGE in ALTER TABLE?

    MODIFY changes column definition without renaming, while CHANGE can rename the column and modify its definition.

  4. Can you drop a column that has constraints?

    Yes, but you may need to drop the constraint first, or use CASCADE option depending on the database system.

  5. How do you add a UNIQUE constraint to an existing column?

    Use: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name);

  6. What happens to existing data when you modify a column?

    Existing data is preserved if compatible with new definition, otherwise conversion occurs or error is raised.

  7. How do you view the structure of a table?

    Use DESCRIBE table_name; or SHOW COLUMNS FROM table_name; commands.

  8. Can ALTER TABLE operations be rolled back?

    In most databases, DDL commands like ALTER TABLE are auto-committed and cannot be rolled back.