Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
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
- Start
- Import mysql.connector module
- Establish connection to MySQL database
- Create cursor object
- Execute ALTER TABLE commands for different operations
- Commit the changes
- Display table structure to verify changes
- Close cursor and connection
- 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
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.
How do you add a column with a default value?
Use: ALTER TABLE table_name ADD COLUMN column_name datatype DEFAULT default_value;
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.
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.
How do you add a UNIQUE constraint to an existing column?
Use: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name);
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.
How do you view the structure of a table?
Use DESCRIBE table_name; or SHOW COLUMNS FROM table_name; commands.
Can ALTER TABLE operations be rolled back?
In most databases, DDL commands like ALTER TABLE are auto-committed and cannot be rolled back.