1.4.4.8 Altering Tables

Note: The alter() method is only available with the MySQL cursor. The other databases do not support the ALTER SQL command.

The alter() method is used to add or remove columns from a table. It looks like this:

alter( table, mode, name, type, [autoExecute=None],)
table
The table to alter
mode
Can be 'add' or 'drop' depending on whether a column is to be added or dropped
name
The name of the column to add or drop
type
The type of the column to add or None if you are dropping a column. Should be a string representing any of the column types mentioned in the table at the start of this module's documentation.
autoExecute
If False the function returns the SQL string to perform the desired operations. If True the SQL is executed and the results converted and returned in the appropriate form. If not specified takes the value specifed in the cursor which by default is True

Here is an example where we add one column and drop another.

>>> if cursor.type == 'mysql':
...     cursor.alter('test', 'add', 'TestColumn', 'String')
...     print "Added a String Column named 'TestColumn' to the 'test' table."
...     cursor.alter('test', 'drop', 'TestFLOAT')
...     print "Dropped the 'TestFLOAT' Column from the 'test' table."

See About this document... for information on suggesting changes.