The ALTER statement in SQL is one of the Data Definition Language-DDL statements along with the CREATE, DROP, TRUNCATE, COMMIT and others.
The ALTER statement changes the structure or schema of an already created database table by adding or removing one or more columns.
The ALTER statement can be used to change several other attributes of the tables such as the name of the table and name of the columns.
The ALTER also adds or removes one or more constraints and indexes as well.
A python program can execute an ALTER statement using the PyMySQL.
Example
python
# import the pymysql module
import pymysql
# Making connection to the MySQL Server
hostIP = "127.0.0.1"
userName = "root"
userPassword = ""
database = "test"
charset = "utf8mb4"
cursorType = pymysql.cursors.DictCursor
con = pymysql.connect(host=hostIP,
user=userName,
password=userPassword,
db=database,
charset=charset,
cursorclass=cursorType,
autocommit=True)
try:
# Creation of cursor object
cursorObject = con.cursor()
# Alter the student table by adding one more column
alterStatement = "ALTER TABLE Student ADD courseid2 int(11);"
# Execute the SQL ALTER statement
cursorObject.execute(alterStatement)
# Verify the new schema by issuing a DESCRIBE statament
descibeStatement = "DESC Student"
# Execute the SQL SELECT query
cursorObject.execute(descibeStatement)
# Fetch the updated row
columns = cursorObject.fetchall()
# Print the updated row...
for column in columns:
print(column)
except Exception as e:
print("Exeception occured:{}".format(e))
finally:
con.close()
We'd like to use Google Analytics cookies to count visits and see which tutorials are useful.
They are only set if you accept. We don't use advertising cookies and we don't sell your data.
You can change your choice any time from “Your privacy choices” at the bottom of every page.
Privacy Policy
Your privacy choices
Your browser sent a Global Privacy Control signal, so analytics is off unless you turn it on here.
Strictly necessary
Remembers this choice in your browser. No cookies, nothing sent to anyone.Always on