python-mysqlHow do I add a column to a MySQL table using Python?
To add a column to a MySQL table using Python, you need to use the ALTER TABLE statement. This statement is used to modify the structure of an existing table. For example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY"
mycursor.execute(sql)
print(mycursor.rowcount, "record(s) affected")
This will add a column named id
to the customers
table with an auto-incrementing integer as the primary key. The output will be 1 record(s) affected
.
Code explanation
import mysql.connector
: imports the MySQL Connector Python module.mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword")
: connects to the MySQL database.mycursor = mydb.cursor()
: creates a cursor object.sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY"
: the SQL statement to add a column to thecustomers
table.mycursor.execute(sql)
: executes the SQL statement.print(mycursor.rowcount, "record(s) affected")
: prints the number of records affected.
Helpful links
More of Python Mysql
- How do I connect to XAMPP MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...